Bash脚本错误检查使用字数和awk

需要一个灯我的脚本我正在做一个字数在一个variables得到一个0或更大的值,但它似乎脚本是在这个variables函数打破count_check = wc -l $TABLE_CHECKS | awk '{print $1}' wc -l $TABLE_CHECKS | awk '{print $1}'if [$ count_check -eq 0],请参阅下面的代码。

 #!/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 = , == . 

需要一些专家的帮助,因为这需要更多的时间比其他方式来实现这一点是受欢迎的,因为我是有限的脚本。

提前致谢 !

终止你的awk语句,并在使用bash时总是使用正确的引号。

最后,“[”作为Bourne Shell sh test ; 在编写Bourne-Again Shell( bash )脚本时使用“[[”。

Grepexpression式在所有系统上的工作方式可能不一样。 我试图让你更通用。

 #!/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 

你已经发现你的问题是set -egrep之间的任何不匹配的交互。 你可以加上|| true 为了避免这种情况,请参阅下文。

而不是计算文件中的行,您可以简单地testing文件中是否有任何内容:

 if [ -s "TABLE_CHECKS" ] ; then NEW_TABLE_CHECKS=table_checks-`date +%Y-%m-%d_%Hh%Mm%Ss`.txt echo "Error on one or more tables. Check output file: $NEW_TABLE_CHECKS" mv $TABLE_CHECKS $NEW_TABLE_CHECKS exit 1 fi 

更好的是,通过把它放在if避免grep / set -e行为:

 if mysqlcheck -e -c --all-databases | grep -E '(error|Error)' > $TABLE_CHECKS ; then NEW_TABLE_CHECKS=table_checks-`date +%Y-%m-%d_%Hh%Mm%Ss`.txt mv $TABLE_CHECKS $NEW_TABLE_CHECKS echo "Error on one or more tables. Check output file: $NEW_TABLE_CHECKS. Contents of file follow:" cat $NEW_TABLE_CHECKS exit 1 fi