我相信我是在一个子subshell中调用exit,它会使我的程序继续运行:
#!/bin/bash
grep str file | while read line
do
exit 0
done
echo "String that should not really show up!"你知道我怎么才能离开主程序吗?
发布于 2012-11-10 09:14:40
您可以简单地重新构造以避免子外壳--或者更确切地说,在子外壳内运行grep而不是while read循环。
#!/bin/bash
while read line; do
exit 1
done < <(grep str file)请注意,<()是仅限bash的语法,不能与/bin/sh一起使用。
发布于 2012-11-10 09:13:45
通常,您可以检查派生的子see的返回代码,以查看main 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!"将不会打印该消息,因为子外壳程序已退出,代码为1。
发布于 2012-11-10 09:18:30
您可以通过从子shell向shell发送一个信号来“退出”shell:用kill -1 $PPID替换exit 0
但是我不推荐这种方法,我建议你的subshell返回一个特殊的有意义的值,比如exit 1
#!/bin/bash
grep str file | while read line
do
exit 1
done
exit 0然后你就可以通过$检查子外壳的返回值了吗?
像subshell.sh ;if [[ $? == 1 ]]; then exit 1 ;fi一样
或者干脆用subshell.sh || exit
https://stackoverflow.com/questions/13318193
复制相似问题