退出在bash中不起作用

时间:2012-09-04 14:49:43

标签: bash

下面是bash脚本

#!/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”,但它没有退出退出脚本

为什么退出不起作用?

3 个答案:

答案 0 :(得分:5)

您正在子shell中调用exit,因此即将退出的shell。试试这个:

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

然而,这将从名为callee的任何shell中退出。您可能希望使用return代替exit从函数返回。

答案 1 :(得分:3)

当您在()中运行命令时,您将生成一个子shell。因此,当您在该子shell中调用exit时,您只是退出它,而不是您的顶级脚本。

答案 2 :(得分:0)

因为圆形的paredenthesis会创建一个新的嵌套shell,它将以exit退出。

相关问题