关于set -e

set命令的-e参数,linux自带的说明如下:
"Exit immediately if a simple command exits with a non-zero status."
也就是说,在"set -e"之后出现的代码,一旦出现了返回值非零,整个脚本就会立即退出。有的人喜欢使用这个参数,是出于保证代码安全性的考虑。但有的时候,这种美好的初衷,也会导致严重的问题。

真实案例:
脚本a.sh开头使用了"set -e",且能正常运行。在几个月或更久以后,因需求升级,在脚本中增加了3行hadoop操作:
#!/bin/bash
set -e
...
/home/work/.../hadoop dfs -rmr /app/.../dir
/home/work/.../hadoop dfs -mkdir /app/.../dir
/home/work/.../hadoop dfs -put file_1 /app/.../dir/
...
这几行hadoop命令逻辑很简单:在hdfs上清除并新建一个目录,并将一份本地文件推送至这个目录,供后续使用。将这几行单拎出来,在命令行下执行,除了提示待删除的目录不存在,并没有什么问题,文件还是会被推送到指定的地方。

但第一次执行这个脚本的时候,却失败退出了,且导致调用该脚本的程序整体退出,造成了严重的后果。原因是hdfs上还没有这个目录,rmr这一行会返回255,这个值被脚本前方的"set -e"捕捉到,直接导致了脚本退出。

新增的代码本身并没有问题,先删除再新建目录,反而是保证数据安全的比较规范的操作,删除命令本身的容错性,可以保证后续命令正常执行。事实是这个脚本有好几百行,且逻辑比较复杂,在增加这几行代码的时候,开发人员已经不记得这个脚本里还有个"set -e"埋伏着了。

可见设置"set -e",在脚本开发过程中可能很有帮助,而在开发完成后,特别是对于后期可能有升级的脚本,则可能是埋下了安全隐患。
07-16
The `set -e` command in shell scripting is used to control the behavior of the script in case an error occurs during execution. Normally, a shell script continues to run even if one of the commands within it fails, which could lead to unexpected results or additional errors. When `set -e` is included at the beginning of a shell script, it tells the shell to exit immediately if any command exits with a non-zero status, which typically indicates an error[^3]. This can be particularly useful for ensuring that a script stops running as soon as something goes wrong, preventing further execution that might rely on the successful completion of previous commands. Here's an example of how `set -e` might be used in a script: ```bash #!/bin/bash set -e # Attempt to create a directory mkdir /path/to/new/directory # Copy files into the new directory cp /path/to/files/* /path/to/new/directory/ ``` In this script, if the `mkdir` command fails (for example, due to permission issues), the script will terminate immediately instead of proceeding to the `cp` command, which would likely fail as well because the directory was not created. It is worth noting that `set -e` has some nuances. For instance, it does not apply to commands that are part of a conditional statement such as `if`, `while`, or `until` loops, or to commands that follow an `!` (not) operator. Additionally, there are other options that can be used alongside `set -e` to fine-tune error handling, such as `set -o pipefail`, which makes a pipeline return the exit status of the last command to exit with a non-zero status, rather than the exit status of the last command in the pipeline[^3].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值