一、简介
工作中常需要在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 found
2. 使用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 found
3. 使用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”