Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my "exit" command not exit my Bash script?

Tags:

bash

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?

like image 237
wenchiching Avatar asked Jan 16 '23 15:01

wenchiching


2 Answers

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.

like image 172
chepner Avatar answered Jan 18 '23 06:01

chepner


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.

like image 41
zigdon Avatar answered Jan 18 '23 06:01

zigdon