首页 > 解决方案 > 如何在条件命令中立即退出?

问题描述

首先,如果任何命令失败,我们可以使用set -e立即退出 shell 脚本(以非零代码退出)。

但是,我怎样才能在条件语句中立即退出呢?例如:

set -xe

_if_error() {
  'run a bad command' # should exit immediately for this command does not exist
  echo -e "\033[31mUnexpected execution\033[0m"
}

if ! _if_error; then
  echo 'ok'
else
  echo 'bad'
fi

我希望脚本回显ok,不要回显红色Unexpected execution

标签: bashshell

解决方案


推荐阅读