Bash脚本IF和| |创建语法错误
我有一个bash脚本,如果if语句中的一个命令以非零结尾(因此当它以错误退出时),我希望在其中写入一个文件。但是,在下面的代码中,我得到了一个语法错误,结尾出现了意外的“else”。我是否正确地使用了这个错误Bash脚本IF和| |创建语法错误,bash,if-statement,handle,Bash,If Statement,Handle,我有一个bash脚本,如果if语句中的一个命令以非零结尾(因此当它以错误退出时),我希望在其中写入一个文件。但是,在下面的代码中,我得到了一个语法错误,结尾出现了意外的“else”。我是否正确地使用了这个错误 if [[ $f != */.* ]]; then echo "$f" command-one || { echo 'Something went wrong with Command-one at file ' $f ' !' >> ../co
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
你错过了一个
如果[error==0]
您错过了一个,则在的末尾添加code>如果[error==0]
运算符==
和,则在的末尾添加code>=代码>仅用于字符串比较
来自
if [ error == 0 ]
至
if [ $error -eq 0 ]
要比较整数,必须使用这些运算符(从手册页):
及
解释
command-one || { echo 'Something went wrong with Command-one at file '$f ' !' >> ../corrupted.txt && error=1; }
如果command one
返回的退出代码不是0,则将echo
中提到的文本追加到文件./corrude.txt
中,并将变量error
设置为1运算符=
和=代码>仅用于字符串比较
来自
if [ error == 0 ]
至
if [ $error -eq 0 ]
要比较整数,必须使用这些运算符(从手册页):
及
解释
command-one || { echo 'Something went wrong with Command-one at file '$f ' !' >> ../corrupted.txt && error=1; }
如果command one
返回的退出代码不是0,则将echo
中提到的文本附加到文件./corrude.txt
中,并将变量error
设置为1这里处理的问题是
}
是文本,因为它不在表达式的开头。我们通过添加来修复它代码>在它之前
因此,添加一个
就在}
之前,指示命令终止,并将所有变量双引号引为
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 ];
您在这里处理的问题是
}
是文本,因为它不在表达式的开头。我们通过添加来修复它代码>在它之前
因此,添加一个
就在}
之前,指示命令终止,并将所有变量双引号引为
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 ];
包括两个
和-eq
,但仍然会出现相同的错误,包括
和-eq
,但还是出现了同样的错误耶稣,我自己永远也不会想出这个错误。非常感谢,它现在很有魅力。请大家投票给我这个答案,因为我认为这是一件非常不寻常的事情。@Bert:以后一定要用它来修复一些琐碎的语法错误,你的语法错误就是这样被抓住的。而且,没有人是完美的。很高兴你发现它很有用。天哪,我一个人永远也想不到这个。非常感谢,它现在很有魅力。请大家投票给我这个答案,因为我认为这是一件非常不寻常的事情。@Bert:以后一定要用它来修复一些琐碎的语法错误,你的语法错误就是这样被抓住的。而且,没有人是完美的。很高兴你发现它有用。