如何在子 shell 命令失败时终止 shell。
例如:
check(){
if [ $1 -eq $1 2> /dev/null ]; then
echo "returning 0"
return 0
else
echo "returning 1"
return 1
fi
}
if [ "($check $1)" == 1 ]; then
echo "Error: with proper message"
exit
fi
if [ "$1" -le 1000 ] || [ "$2" -ge 10000 ]; then
echo "Error:"
exit
fi
我在这里传递一个字符串,首先是条件失败,其次是条件执行并在命令行“预期整数表达式”中出现错误。 我知道 () 子 shell 命令失败但 shell 没有终止。当子 shell 命令失败时如何退出 shell。
最佳答案
您想测试函数的退出状态。以下内容:
if [ "($check $1)" == 1 ]; then
可能会导致错误。即使你说:
if [ "$(check $1)" == 1 ]; then
不会比较退出状态,即函数的返回值。它会将函数的输出与1
进行比较。
您需要通过以下方式调用您的函数:
check $1
然后通过以下语句检查退出状态:
if [ $? -ne 0 ]; then
echo "Error: with proper message"
exit
fi
(据我所知,这里没有涉及任何子 shell。)
关于linux - 子 shell 命令失败时如何终止 shell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20546740/