嘗試使用狀態代碼退出腳本,但收到“意外的文件結尾”

嘗試使用狀態代碼退出腳本,但收到“意外的文件結尾”

我在 Amazon Linux 上使用 bash shell。我不明白為什麼我的腳本因語法錯誤而崩潰。我的腳本是這樣結束的

chmod 775 $TFILE2
output_file=$( create_test_results_file "$TFILE2" )
(cat $TFILE2; uuencode $output_file $output_file) | mailx -s "$subject" "$to_email"
rm $output_file
echo "sent second email"

#Cleanup
rm $TFILE1
rm $TFILE2
echo "removed files"

# If node exited unsuccessfully, verify we alert the process above.
if [ $rc1 != 0 ]; then exit $rc1 fi
if [ $rc2 != 0 ]; then exit $rc2 fi

當我運行它時,它會印出最後兩個 echo 語句,但在那之後似​​乎就死了

sent second email
removed files
/home/jboss/.jenkins/jobs/springboard/workspace/automated-tests/nodejs/run_tests.sh: line 86: syntax error: unexpected end of file

誰能告訴我為什麼它會因意外的文件結束錯誤而死亡?

答案1

簡而言之,這fi需要是一個單獨的命令,因此您需要分號:

if [ $rc1 != 0 ]; then exit $rc1; fi
if [ $rc2 != 0 ]; then exit $rc2; fi

您應該引用變量,並且由於您正在比較整數,因此請使用適當的運算符:

if [ "$rc1" -ne 0 ]; then exit "$rc1"; fi
if [ "$rc2" -ne 0 ]; then exit "$rc2"; fi

儘管這裡的行為略有不同:空值將被視為等於 0(其中!=會認為它們不同)。

相關內容