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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With