Linux – Bash scripting error checking using word count and awk

bashlinuxshell-scripting

Need a light on my script I am doing a word count on a variable get a 0 or bigger value but it seems the script is breaking at on this variable function
count_check=wc -l $TABLE_CHECKS | awk '{print $1}' or the if [ $count_check -eq 0 ] please see my code below.

#!/bin/bash -x
set -e
set -u


#
# Routine to check integrity of the restored backup
#


TABLE_CHECKS="$(mktemp -p .)"

mysqlcheck -e -c --all-databases | grep -e error -e Error > $TABLE_CHECKS 

        # if [ $? -eq 0 ]
            # then
              # echo "mysqlcheck running ..."
            # else
              # echo "mysqlcheck error !"
              # exit 1
        # fi

count_check=`wc -l $TABLE_CHECKS | awk '{print $1}'` 
        if [ $count_check -eq 0 ]
            then
              echo "Tables ok..."
            else
              echo "Error on one or more tables. Check  output file: table_checks.txt"
              cat $TABLE_CHECKS > table_checks-`date +%Y-%m-%d_%Hh%Mm%Ss`.txt
              rm -f $TABLE_CHECKS
              exit 1
        fi

rm -f $TABLE_CHECKS

exit 0


I've tried changing the comparison instead of using -eq I was using = , == .

Need some help from the experts as this is taking more time than it needed.Also other ways to achieve that are welcome as I'm limited in scripting.

Thanks in Advance !

Best Answer

Terminate your awk statement and always use proper quoting when using bash.

Finally, "[" as test is for the Bourne Shell sh; use "[[" when writing Bourne-Again Shell (bash) scripts.

Grep expressions may not work the same way on all systems. I've tried to make yours more generic.

#!/bin/bash -x

# don't set flags unless you know you need 'em. 

#
# Routine to check integrity of the restored backup
#

TABLE_CHECKS="table_checks-`date +%Y-%m-%d_%Hh%Mm%Ss`.txt"
mysqlcheck -e -c --all-databases > $TABLE_CHECKS

# grep can do the work you want in one step.
count_check="$(grep -c -E '(error|Error)' $TABLE_CHECKS)"

# What did you get?
echo "count_check is: \"${count_check}\""

# unnecessary indenting makes this hard to read
if [[ $count_check -eq 0 ]]
then
    echo "Tables ok..."
    rm $TABLE_CHECKS
    exit 0
else
    echo "Error on one or more tables. Check output file: ${TABLE_CHECKS}"
    exit 1
fi