1

exit 1用来在发生错误时停止执行 shell 脚本。

外壳脚本

    test() {
    mod=$(($1 % 10))
    if [ "$mod" = "0" ]
    then
        echo "$i";
        exit 1;
    fi
}


for i in `seq 100`
do
    val=`test "$i"`
    echo "$val"
done

echo "It's still running"

为什么它不起作用?如何停止 shell 脚本的执行?

4

2 回答 2

2

正在退出的 shellexit是由命令替换启动的 shell,而不是启动命令替换的 shell。

尝试这个:

for i in `seq 100`
do
    val=`test "$i"` || exit
    echo "$val"
done

echo "It's still running"

您需要显式检查命令替换的退出代码(由变量赋值传递),如果它不为零,则再次调用 exit。


顺便说一句,您可能希望return在函数中使用而不是exit. 让函数调用者决定要做什么,除非错误非常严重以至于没有退出 shell 的逻辑替代方案:

test () {
    if (( $1 % 10 == 0 )); then
        echo "$i"
        return 1
    fi
}
于 2013-04-29T13:18:18.260 回答
1

The exit command terminates only the (sub)shell in which it is executed. If you want to terminate the entire script, you have to check the exit status ($?) of the function and react accordingly:

#!/bin/bash

test() {
    mod=$(($1 % 10))
    if [ "$mod" -eq "0" ]
    then
        echo "$i";
        exit 1;
    fi
}


for i in `seq 100`
do
    val=`test "$i"`
    if [[ $? -eq 1 ]]
    then
      exit 1;
    fi
    echo "$val"
done

echo "It's still running"
于 2013-04-29T13:17:14.753 回答