【问题标题】:Automatically exit when bash command produce return code non zero [duplicate]当bash命令产生非零返回码时自动退出[重复]
【发布时间】:2019-04-28 10:48:51
【问题描述】:

在 bash 中,如果命令行返回码不为零,我们如何使脚本自动退出。例如:

#!/bin/bash

cd /something_something
mv file_a /somedir/file_a # this produce an error
echo $?  # This produce a non-zero output
echo "We should not continue to this line"

我知道我们可以使用#!/bin/bash -x 调试 bash 脚本,但有时脚本太长,运行速度如此之快,我们错过了重要错误。

我不想继续写 [[ $? -ne 0 ]] && run next_command

【问题讨论】:

  • 你可以使用set -e#!/bin/bash -e
  • ^^ + 否则称为“错误退出”标志
  • mv file_a /somedir/file_a || exit?
  • @anubhava 谢谢,这就是我需要的。奇怪的是我的bash --help 没有显示这个选项,不管怎样,它有效。你能把它作为答案吗?
  • 注意BashFAQ #105,描述为什么你要求的是一个坏主意。无法区分“X 返回值 false”和“X 失败”之间的区别,并且很多事情返回非零退出状态的原因实际上并不是失败。更糟糕的是,set -e 有很多启发式方法可以尝试猜测这些情况,它们是 different between different shells (and releases of the same shell),这些差异会导致意外/损坏。

标签: bash


【解决方案1】:

lots of problems 使用set -e。只需使用&& 加入命令,然后使用if 语句测试结果。

if cd /something_something && mv file_a /somedir/file_a; then
    echo $?
    exit
fi
echo "Both cd and mv worked"

【讨论】:

    猜你喜欢
    • 2016-01-01
    • 2017-12-28
    • 2019-11-28
    • 2016-07-11
    • 2021-02-15
    • 2020-10-08
    • 1970-01-01
    • 2020-05-10
    • 2015-09-05
    相关资源
    最近更新 更多