命令||运行代码并退出

时间:2014-04-28 14:56:48

标签: bash shell sh

我运行一个命令,然后执行OR,这样如果命令失败,将执行代码块:

#!/bin/sh
test || (
 echo "Test failed, exit!"
 exit 1
)
echo "Test succeeded!"

这样可行,但脚本只是继续而不退出,Test succeeded仍然打印出来。

我尝试使用exec

test || exec <<EOS
  echo "Test failed, exit!"
EOS

但是这根本不会运行heredoc,也不会停止脚本的其余部分......

我是shell脚本的新手。

2 个答案:

答案 0 :(得分:5)

这是因为(..)启动子shell。你在里面做的任何与你相关的过程只会影响那个子shell。

相反,请使用{..}分组:

#!/bin/sh
test || {
 echo "Test failed, exit!"
 exit 1
}
echo "Test succeeded!"

当您 想要包含效果时,(..)行为非常有用,例如

for dir in */
do 
  ( cd "$dir" && make )  # This 'cd' will be contained inside the ()
done

这可以防止您必须跟踪是否能够进入,因此您是否必须cd ..将其恢复到原来的状态。

答案 1 :(得分:3)

@thatOtherGuy给了你正确答案。

如果{ grouped block; }长于一行,我会鼓励你,使用if

if test; then
    echo "test succeeded"
else
    echo "test failed, exit" >&2
    exit 1
fi
与IMO相比,可读性较差。

test || {
    echo "test failed, exit" >&2
    exit 1
}
echo "test succeeded"
相关问题