我是 shell 腳本和使用多個 rm 命令編寫腳本的新手。該腳本必須刪除某些目錄中的檔案。我想捕獲每個命令的退出狀態,並在失敗時返回退出狀態並繼續執行下一個命令。有人可以幫我改正我的腳本嗎?
#!/bin/bash
PATH1=mydir/folder/
PATH2=mydir/newfolder/
HOST= hostname | grep -o "[0-9]*" | head -1
case "$HOST" in
01)echo "Removing files in server 1.."
find $PATH1/logs -maxdepth 1 -mtime +30 -type f \( -name "*.log*" -o -name "*.out*" \) -exec rm -f {} \;
find $PATH1/logs -maxdepth 1 -mtime +30 -type f \( -name "*.log*" -o -name "*.out*" \) -exec rm -f {} \;
RETVAL=$?
;;
02)echo "Remove logfiles in server 02"
find $PATH2/logs -maxdepth 1 -mtime +30 -type f \( -name "*.log*" -o - name "*.out*" \) -exec rm -f {} \;
find $PATH2/logs -maxdepth 1 -mtime +30 -type f \( -name "*.log*" -o -name "*.out*" \) -exec rm -f {} \;
RETVAL=$?
;;
*)
echo "Removal of log files is complete"
esac
答案1
anecho $?
應該回傳前一個指令的狀態。所以你可能會想使用
if [ ! $? -eq 0 ]; then
echo "command failed"
else
echo "command success"
fi