1、問題
在shell腳本裡面有時候我們需要判斷上一個程式有沒有執行成功,比如用chomd 777 file指令,我們可以用通過if [ $? != 0 ]判斷
$?這裡表示上一次運作的結果
2、代碼實作
#!/bin/bash
test()
{
return 2;
}
test
result=$?
echo "result is:"$result
echo "chenyu"
#這裡不能寫成if [$? != 0]或者if [$? != 0 ]或者if[ $? != 0]
if [ $? != 0 ]; then
echo "last exe fail"
exit 1
else
echo "last exe success"
fi
3、運作結果
1. result is:2
2. chenyu
3. last exe success