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

and this is the result:

+ 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!

I see the command exit, but it doesn't exit the script – why doesn't exit work?

3 Answers 3

6

You are calling exit from inside a subshell, so that's the shell that is exiting. Try this instead:

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

This, however, will exit from whatever shell called callee. You may want to use return instead of exit to return from the function.

Sign up to request clarification or add additional context in comments.

Comments

3

When you run a command in () you're spawning a subshell. So when you call exit within that subshell, you're just exiting it, and not your top level script.

Comments

2

Because round paredenthesis creates a new nested shell, which is exited with exit.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.