加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

bash – 使用set -e,是否可以忽略某些命令的错误?

发布时间:2020-12-16 01:18:24 所属栏目:安全 来源:网络整理
导读:参见英文答案 Bash ignoring error for a particular command6个 我有一个bash脚本,我想全局启用set -e. 但是不是一直禁用它并重新启用它,我想知道是否有一种方法可以选择性地禁用错误处理. 例如,从systemd运行的命令可以在减号之前忽略错误. bash有同等效力
参见英文答案 > Bash ignoring error for a particular command6个
我有一个bash脚本,我想全局启用set -e.

但是不是一直禁用它并重新启用它,我想知道是否有一种方法可以选择性地禁用错误处理.
例如,从systemd运行的命令可以在减号之前忽略错误. bash有同等效力吗?

例如

#!/bin/bash

set -e

WAN_IF=eth2

# Ignore error on next line
tc qdisc del dev ${WAN_IF} root

# I want errors to stop the script on this line
tc qdisc add dev ${WAN_IF} root handle 1: htb default 10

...
etc

由于需要启用/禁用很多,我不想继续执行以下操作:

set +e
tc qdisc del dev ${WAN_IF} root

# I want errors to stop the script on this line
set -e
tc qdisc add dev ${WAN_IF} root handle 1: htb default 10
...
添加|| :(或其他任何保证不会失败,但这是最简单的)到命令的结尾.

虽然很多人只是告诉你set -e不值得,因为它没有你想象的那么有用(并导致这样的问题),手动错误检查是一个更好的策略.

(我不在那个阵营中,但是我越是遇到这样的问题,我觉得有一天我可能会到达那里.)

从thatotherguy的评论解释set -e的主要问题之一:

The problem with set -e isn’t that you have to be careful about which commands you want to allow to fail. The problem is that it doesn’t compose. If someone else reads this post and uses source yourfile || : to source this script while allowing failure,suddenly yourfile will no longer stop on errors anywhere. Not even on failing lines after an explicit set -e.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读