Bash脚本IF和||创建语法错误

时间:2017-02-20 10:25:53

标签: bash if-statement handle

我有一个bash脚本,如果IF语句中的一个命令以非零结尾(因此当它以错误退出时),我希望写入文件。但是,如果出现以下情况,我会收到意外的语法错误" else"在末尾。我是否正确使用此错误写作?

-Wall -Werror -Wextra -std=c++11 -O3

3 个答案:

答案 0 :(得分:2)

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

的典型示例

}是字面意思,因为它不在表达式的开头。我们通过在其前添加;来解决此问题。

所以在;之前添加}以指示命令终止并将所有变量双引号为,

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 ];

答案 1 :(得分:0)

您在;

结束时错过了if [ error == 0 ]

答案 2 :(得分: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返回0以外的退出代码,则将echo中提到的文字附加到文件../corrupted.txt并将变量error设置为1