为什么我的“exit”命令无法退出Bash脚本?

6

I have this Bash script:

#!/bin/bash
set -x
function doSomething() {
    callee
    echo "It should not go to here!"
}

function callee() {
    ( echo "before" ) && (echo "This is callee" && exit 1 )                                                                                   
    echo "why I can see this?"
}


doSomething

这是结果:

+ set -x
+ doSomething
+ callee
+ echo before
before
+ echo 'This is callee'
This is callee
+ exit 1
+ echo 'why I can see this?'
why I can see this?
+ echo 'It should not go to here!'
It should not go to here!

我看到了命令exit,但它并没有退出脚本——为什么exit不起作用?

3个回答

6
您正在从子shell中调用exit,所以退出的是该shell。请尝试使用以下命令代替:

function callee() {
    ( echo "before" ) && { echo "This is callee" && exit 1; }                                                                                   
    echo "why I can see this?"
}

不过,这将会退出调用callee的任何 shell。你可能想要使用return而不是exit来从函数中返回。


3
当你在()中运行一个命令时,你正在生成一个子shell。因此,当你在该子shell中调用exit时,你只是退出了该子shell,而不是你的顶层脚本。

2

因为圆括号会创建一个新的嵌套Shell,使用exit命令可以退出该shell。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接