2

我相信我在一个子shell中调用 exit 会导致我的程序继续:

#!/bin/bash
grep str file | while read line
do
        exit 0
done
echo "String that should not really show up!"

知道如何退出主程序吗?

4

3 回答 3

4

您可以简单地重组以避免子shell - 或者更确切地说,grep在子shell 内部运行而不是while read循环。

#!/bin/bash
while read line; do
  exit 1
done < <(grep str file)

请注意,这<()是仅限 bash 的语法,不适用于/bin/sh.

于 2012-11-10T01:14:40.440 回答
1

通常,您可以检查生成的子 shell 的返回码,以查看主 main 是否应该继续。

例如:

#!/bin/bash

grep str file | while read line
do
        exit 1
done

if [[ $? == 1 ]]; then
    exit 1
fi

echo "String that should not really show up!"

不会打印消息,因为 subshel​​l 以 code 退出1

于 2012-11-10T01:13:44.867 回答
0

您可以通过从您的子外壳发送信号来“退出”您的外壳:替换exit 0kill -1 $PPID

但我不推荐这种方法。我建议你的 subshel​​l 返回一个特殊的意义值,比如exit 1

#!/bin/bash
grep str file | while read line
do
        exit 1
done
exit 0

那么你可以通过 $ 来检查你的 subshel​​l 的返回值吗?

喜欢subshell.sh ;if [[ $? == 1 ]]; then exit 1 ;fi

或者干脆subshell.sh || exit

于 2012-11-10T01:18:30.057 回答