高密建设局网站,东莞家具行业营销型网站建设多少钱,wordpress 开发者模式,上海保洁服务网站建设一、简介
工作中常需要在linux环境下使用shell脚本自动化运行多条命令#xff0c;在顺序执行多条命令时#xff0c;需要在前一条命令运行失败时立刻结束脚本#xff0c;停止运行接下来的其他命令。 本文介绍了三种实现该目标的方法#xff0c;分别是#xff1a;使用…一、简介
工作中常需要在linux环境下使用shell脚本自动化运行多条命令在顺序执行多条命令时需要在前一条命令运行失败时立刻结束脚本停止运行接下来的其他命令。 本文介绍了三种实现该目标的方法分别是使用命令执行控制符使用set -e设置shell options和使用trap do_somthing ERR捕捉ERR信号进行自定义处理。
二、代码示例
1. 使用命令执行控制符
命令之间使用连接实现逻辑与的功能只有前面的命令成功运行才会继续运行之后的命令。 命令示例
# command without error
echo first command echo second command echo third command运行结果如下
first command
second command
third command若某条命令存在错误无法运行则会立即结束不再执行之后的命令。 命令示例
# command with error
echo first command echooo second command echo third command运行结果如下
first command
echooo: command not found2. 使用set -e命令
set -e命令可以设置shell在运行时如果遇到管道返回非0状态程序成功运行退出返回0则立即退出。管道可能由单个简单命令列表或复合命令组成。 set -e Exit immediately if a pipeline (see Pipelines), which may consist of a single simple command (see Simple Commands), a list (see Lists of Commands), or a compound command (see Compound Commands) returns a non-zero status. main.sh脚本示例
#!/usr/bin/bash
# command without error
set -e
echo first command
echo second command
echo third command运行main.sh后的结果如下
first command
second command
third command若main.sh脚本中存在错误无法运行则会退出脚本。例如
#!/usr/bin/bash
set -e
echo first command
# command with error
echooo second command
echo third command运行main.sh后的结果如下
first command
./main.sh: line 4: echooo: command not found3. 使用trap命令
在What does ‘set -e’ mean in a Bash script? 中网友给出了另一个用于在shell中中断错误命令运行的方法即使用trap do_something ERR 命令。 trap命令是一个shell内建命令它用来在脚本中指定信号如何处理。例如trap echo error exit ERR命令就是设置在shell脚本运行时若遇到ERR信号则先使用echo命令打印error然后退出。
main.sh脚本示例
#!/usr/bin/bash
# command without error
trap echo error exit ERR
echo first command
echo second command
echo third command运行main.sh后的结果如下
first command
second command
third command若main.sh脚本中存在错误无法运行则会先打印error然后退出脚本。例如
#!/usr/bin/bash
trap echo error exit ERR
echo first command
# command with error
echooo second command
echo third command运行main.sh后的结果如下
first command
./main.sh: line 5: echooo: command not found
error三、参考
[1]. linux中的分号和|和||说明与用法 [2]. What does ‘set -e’ mean in a Bash script? [3]. Linux trap用法介绍 var code “ae301d0e-c65a-4bcc-b771-f85ac0074d55”