`exit` script does not exit inside parentheses

Here is a simple question. Why doesn't this behave the way I think:

(echo "Test 1"; exit) && echo "Test 2" 

... or...

 VAR1=1 VAR2=2 [ $VAR1 == $VAR2 ] || (echo '$VAR1 does not equal $VAR2, exiting.'; exit) echo -e 'Well, I\'m still alive yo!' 

Running either of these two snippets will continue to execute the script, despite the explicit exit .

Obviously, parentheses for some reason affect the team, so my question is: why?

+6
source share
4 answers

Parentheses execute their contents in a subshell, so it leaves the sub-context.

Usually you achieve the same effect either with another && , or with {} instead of () .

 { echo "Test 1"; exit; } && echo "Test 2" 

or

 echo "Test 1" && exit && echo "Test 2" 
+7
source

The content ( ... ) is executed in a subshell, so you just exit this shell. This approach should work better for you, and it’s easier for you to read the next person’s support and open your script:

 VAR1=1 VAR2=2 if [ $VAR1 == $VAR2 ] ; then echo -e "Well, I'm still alive yo!" else echo "$VAR1 does not equal $VAR2, exiting." exit fi 
+1
source

Just remove the parentheses and it should do what you want.

The brackets are equivalent to putting their contents in another shell script, where exit simply exits the shell script.

+1
source

From http://tldp.org/LDP/abs/html/subshells.html

The list of commands embedded in parentheses is executed as a subshell.

 ( command1; command2; command3; ... ) 

The code block between curly braces does not start a subshell.

 { command1; command2; command3; . . . commandN; } 

In the first case, the output is performed by a subordinate shell, which terminates and returns control to the calling shell.

0
source

Source: https://habr.com/ru/post/957764/


All Articles