退出在bash中不起作用

wen*_*ing 4 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
Run Code Online (Sandbox Code Playgroud)

这就是结果......

+ 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!
Run Code Online (Sandbox Code Playgroud)

我看到命令"exit",但它没有退出退出脚本

为什么退出不起作用?

che*_*ner 5

你是exit从子shell 中调用的,所以这是正在退出的shell.试试这个:

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

但是,这将退出所谓的shell callee.您可能希望使用return而不是exit从函数返回.