我有一个shell脚本,其中我有3个命令。我想在第一条命令成功的情况下执行第二条命令,这可以通过使用 command1
&&amp。command2
如果发生任何错误,我想 command2
以非零代码退出。我还想执行 command3
总归 command2
是成功还是失败。
到现在为止已经做到了这一点。
#!/bin/bash
(command1 && command2)
command3
Command2
是一个docker组成起来的命令 不想在detach模式下执行。
如何能做到这一点?
要想一个命令接一个命令的运行,不管返回的是哪个退出代码,可以尝试。
command1 && command2 ; command3
另一种方法,记住,你要检索一个非零的退出代码。command2
失败,但仍能保持脚本的运行。
#!/bin/bash
set +e
command1
if [ $? -eq 0 ]; then
command2 2>&1 || echo "command2 failed with $? exit code"
fi
command3
hads0m是在正确的轨道上。
#!/bin/bash
set +e
command1
result=$?
if [ $result -eq 0 ]; then
command2
fi
command3
if [ $result -ne 0 ]; then
echo "command1 failed." >&2
exit $result
fi