相关疑难解决方法(0)

设置errexit选项时检测shell退出代码的正确方法

我更喜欢编写可靠的shell代码,因此总是设置errexit和nounset.

以下代码将在bad_command行停止

#!/bin/bash
set -o errexit ; set -o nounset
bad_command # stop here
good_command
Run Code Online (Sandbox Code Playgroud)

我想抓住它,这是我的方法

#!/bin/bash
set -o errexit ; set -o nounset
rc=1
bad_command && rc=0 # stop here
[ $rc -ne 0 ] && do_err_handle
good_command
Run Code Online (Sandbox Code Playgroud)

有没有更好或更清洁的方法

我的答案:

#!/bin/bash
set -o errexit ; set -o nounset
if ! bad_command ; then
  # error handle here
fi
good_command
Run Code Online (Sandbox Code Playgroud)

shell

42
推荐指数
5
解决办法
2万
查看次数

标签 统计

shell ×1