I have a script, that does not exit when I want it to.
An example script with the same error is:
#!/bin/bash
function bla() {
return 1
}
bla || ( echo '1' ; exit 1 )
echo '2'
I would assume to see the output:
:~$ ./test.sh
1
:~$
But I actually see:
:~$ ./test.sh
1
2
:~$
Does the ()
command chaining somehow create a scope? What is exit
exiting out of, if not the script?
Best Answer
()
runs commands in the subshell, so byexit
you are exiting from subshell and returning to the parent shell. Use braces{}
if you want to run commands in the current shell.From bash manual:
It's worth mentioning that the shell syntax is quite consistent and the subshell participates also in the other
()
constructs like command substitution (also with the old-style`..`
syntax) or process substitution, so the following won't exit from the current shell either:While it may be obvious that subshells are involved when commands are placed explicitly inside
()
, the less visible fact is that they are also spawned in these other structures:command started in the background
doesn't exit the current shell because (after
man bash
)the pipeline
still exits only from the subshell.
However different shells behave differently in this regard. For example
bash
puts all components of the pipeline into separate subshells (unless you use thelastpipe
option in invocations where job control is not enabled), but AT&Tksh
andzsh
run the last part inside the current shell (both behaviours are allowed by POSIX). Thusdoes basically nothing in bash, but exits from the zsh because of the last
exit
.coproc exit
also runsexit
in a subshell.