首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从子shell中退出shell

从子shell中退出shell
EN

Stack Overflow用户
提问于 2012-11-10 09:02:58
回答 3查看 2.5K关注 0票数 1

我相信我是在一个子subshell中调用exit,它会使我的程序继续运行:

代码语言:javascript
复制
#!/bin/bash
grep str file | while read line
do
        exit 0
done
echo "String that should not really show up!"

你知道我怎么才能离开主程序吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-11-10 09:14:40

您可以简单地重新构造以避免子外壳--或者更确切地说,在子外壳内运行grep而不是while read循环。

代码语言:javascript
复制
#!/bin/bash
while read line; do
  exit 1
done < <(grep str file)

请注意,<()是仅限bash的语法,不能与/bin/sh一起使用。

票数 3
EN

Stack Overflow用户

发布于 2012-11-10 09:13:45

通常,您可以检查派生的子see的返回代码,以查看main main是否应该继续。

例如:

代码语言:javascript
复制
#!/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

票数 1
EN

Stack Overflow用户

发布于 2012-11-10 09:18:30

您可以通过从子shell向shell发送一个信号来“退出”shell:用kill -1 $PPID替换exit 0

但是我不推荐这种方法,我建议你的subshell返回一个特殊的有意义的值,比如exit 1

代码语言:javascript
复制
#!/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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13318193

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档