如何在第一个命令失败后在一行中运行多个其他 bash 命令

如何在第一个命令失败后在一行中运行多个其他 bash 命令

当某些命令(来自 bash 脚本内部)失败时,将会发出错误消息,然后退出脚本。

让我们只展示示例(将最后一个命令包装到回显字符串中以便于测试):

$ which which || echo "failed"; echo "exit 1"
/usr/bin/which
exit 1
$ which which1 || echo "failed"; echo "exit 1"
failed
exit 1

如您所见,示例在任何情况下都会 /exit/。相反,它只应在第二种情况下退出。如何解决这个问题以实现所需的行为?我想 bash 中内置了一些选项,用于对命令项 #2 和 #3 进行分组...

答案1

您可以使用子 shell,如您的答案

which which1 || ( echo "failed"; echo "exit 1" )

或者将命令分组而不启动单独的子 shell:

which which1 || { echo "failed"; echo "exit 1"; }

注意:有关{ }vs 的更多详细信息( ),请参阅的“复合命令”和“命令执行环境”部分man bash

或者,您可以做这样的事情来构建更复杂的处理程序:

#!/bin/bash

which "$1"

if [[ $? != 0 ]]; then
  echo "Failed: Exited with $?"
  exit 1
else
  echo "Worked!"
fi

您也可以将其写为一个函数:

#!/bin/bash
runme(){
  "$@"
  if [[ $? != 0 ]]; then
    echo "Failed: Exited with $?"
    exit 1
  else
    echo "Worked!"
  fi
}

runme which which1

或者,更简单地如果您不需要显示退出状态:

#!/bin/bash
runme(){
  if "$@"; then
    echo "Worked"
  else
    echo "Failed!"
    exit 1
  fi
}

runme which which

答案2

这显然可以使用花括号(=对命令进行分组;结尾的分号是必须的)来解决:

$ which which || { echo "failed"; echo "exit 1"; }
/usr/bin/which
$ which which1 || { echo "failed"; echo "exit 1"; }
failed
exit 1

显然,使用圆括号可以解决这个问题(=调用子 shell;不推荐):

$ which which || ( echo "failed"; echo "exit 1" )
/usr/bin/which
$ which which1 || ( echo "failed"; echo "exit 1" )
failed
exit 1

bash 中的命令分组是使用花括号或圆括号完成的,但本质上略有不同,这可能会增加第二种情况的执行时间,并且需要第一种情况稍微更精确的编码语法。

相关内容