我是 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