[英]How to handle errors in shell script
我正在编写Shell脚本来安装我的应用程序。 我的脚本中有更多命令,例如复制,解压缩,移动,如果等等。 如果任何命令失败,我想知道该错误。 我也不想发送零以外的退出代码。
脚本安装顺序(root-file.sh):
./script-to-install-mongodb
./script-to-install-jdk8
./script-to-install-myapplicaiton
示例脚本文件:-
cp sourceDir destinationDir
unzip filename
if [ true]
// success code
if
我想通过使用变量或任何消息来了解我的脚本命令是否在root-file.sh中失败。
我不想编写代码来检查每个命令状态。 有时cp或mv命令可能由于目录无效而失败。 在脚本执行结束时,我想知道所有命令都已成功执行还是出错?
有办法吗?
注意:我使用的是Shell脚本而不是bash
/ *最后一个命令的状态存储在特殊变量$?中,您可以为$?定义变量。 做出口var = $? * /
unzip filename
export unzipStatus=$?
./script1.sh
export script1Status=$?
if [ !["$unzipStatus" || "$script1Status"]]
then
echo "Everything successful!"
else
echo "unsuccessful"
fi
linux shell脚本中的异常处理可以如下进行
command || fallback_command
如果您有多个命令,则可以执行
(command_one && command_two) || fallback_command
在这里fallback_command
可以是文件中的echo
或log
详细信息等。
我不知道您是否尝试过将set -x
放在脚本顶部以查看详细的执行情况。
当您使用Shell脚本实现此功能时,没有太多外部工具。 那么默认的$? 应该有所帮助。 您可能要检查脚本之间的检索值。 该代码将如下所示:
./script_1
retval=$?
if $retval==0; then
echo "script_1 successfully executed ..."
continue
else;
echo "script_1 failed with error exit code !"
break
fi
./script_2
让我知道这是否为您的方案增加了任何价值。
要在这里给我2美分。 像这样运行你的shell
sh root-file.sh 2> errors.txt
来自errors.txt的grep模式
grep -e "root-file.sh: line" -e "script-to-install-mongodb.sh: line" -e "script-to-install-jdk8.sh: line" -e "script-to-install-myapplicaiton.sh: line" errors.txt
上面的grep命令的输出将显示其中有错误的命令以及行号。 可以说输出是:
test.sh:第8行:file3:权限被拒绝
您可以去检查出现问题的行号(这里是8)。 请参考此行号。 在vi中 。
或者这也可以是自动化的: 您的shell脚本中grep特定行。 grep行在这里有问题8 。
head -8 test1.sh |tail -1
希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.