如何避免在特定命令失败时退出shell脚本

rod*_*dee 4 shell sh

以下脚本使用该-e选项运行,因此如果其中的任何命令失败,它将退出:

#!/bin/sh -e
command1 #script should fail if command1 fails
command2 #script should NOT fail if command2 fails
command3 #script should fail if command3 fails
Run Code Online (Sandbox Code Playgroud)

如何让脚本失败command2

Joh*_*ica 11

command1
command2 || true
command3
Run Code Online (Sandbox Code Playgroud)


gle*_*man 5

您可以根据需要关闭设置:

#!/bin/sh
set -e

command1 #script should fail if command1 fails

set +e
command2 #script should NOT fail if command2 fails
set -e

command3 #script should fail if command3 fails
Run Code Online (Sandbox Code Playgroud)

  • 在某些情况下可能是必要的(也许您需要根据 `command2` 的确切退出状态采取不同的操作)。 (2认同)