Bash 脚本 IF 和 ||造成语法错误

Bash script IF and || creates syntax error

我有一个 bash 脚本,如果 IF 语句中的命令之一以非零结尾(因此当它因错误退出时),我希望写入文件。但是,对于以下内容,我得到一个语法错误,最后出现意外的 "else" 。我用这个错误写对了吗?

if [[ $f != */.* ]]; then
        echo "$f"
        command-one || { echo 'Something went wrong with Command-one at file ' $f ' !' >> ../corrupted.txt } || error=1
        command-two || { echo 'Something went wrong with Command-two at file ' $f ' !' >> ../corrupted.txt } || error=1
        command-three || { echo 'Something went wrong with Command-three at file ' $f ' !' >> ../corrupted.txt } || error=1
        if [ error == 0 ]
        then
            echo "====================================================" >> ../ok.txt
            echo "All went well with: " $f >> ../ok.txt
        fi
        error=0
    else
        echo "This file is corrupted: " $f >> ../corrupted.txt
    fi

您错过了 if [ error == 0 ]

末尾的 ;

运算符==!=仅用于字符串比较

来自

if [ error == 0 ]

if [ $error -eq 0 ]

要比较整数,您必须使用这些运算符(来自手册页):

   INTEGER1 -eq INTEGER2
          INTEGER1 is equal to INTEGER2

   INTEGER1 -ge INTEGER2
          INTEGER1 is greater than or equal to INTEGER2

   INTEGER1 -gt INTEGER2
          INTEGER1 is greater than INTEGER2

   INTEGER1 -le INTEGER2
          INTEGER1 is less than or equal to INTEGER2

   INTEGER1 -lt INTEGER2
          INTEGER1 is less than INTEGER2

   INTEGER1 -ne INTEGER2
          INTEGER1 is not equal to INTEGER2

command-one || { echo 'Something went wrong with Command-one at file ' $f ' !' >> ../corrupted.txt && error=1; }
command-two || { echo 'Something went wrong with Command-two at file ' $f ' !' >> ../corrupted.txt && error=1; }
command-three || { echo 'Something went wrong with Command-three at file ' $f ' !' >> ../corrupted.txt  && error=1; }

说明

command-one || { echo 'Something went wrong with Command-one at file '$f ' !' >> ../corrupted.txt && error=1; }

如果 command-one returns 退出代码不是 0 那么,将 echo 中提到的文本附加到文件 ../corrupted.txt 并将变量 error 设置为 1

你这里处理的问题是SC1083 - This {/} is literal. Check expression (missing ;/\n?) or quote it.

的经典例子

} 是文字,因为它不在表达式的开头。我们通过在它之前添加一个 ; 来修复它。

所以在 } 之前添加 ; 以指示 command-termination 和 double-quote 所有变量,

command-one || { echo "Something went wrong with Command-one at file  ${f}  !" >> ../corrupted.txt; } || error=1
command-two || { echo "Something went wrong with Command-two at file  ${f}  !" >> ../corrupted.txt; } || error=1
command-three || { echo "Something went wrong with Command-three at file ${f} !" >> ../corrupted.txt; } || error=1

另一种方法是将比较运算符固定为

if [ $error -eq 0 ];