6

I need braces to specify evaluation priority of expressions, but I don't want braces to create sub-scripts. Look what happens when that example code is ran:

Example script

#!/bin/bash

false || (echo "First" && exit 1)
false || (echo "Second" && exit 2)
exit 3

Output

First
Second

It seems that braces create sub-scripts, where exit doesn't cause the main script to exit.

What is the most elegant way to do what I want? Preferably without blocks and nesting. Thanks!

1 Answers1

12

These () are parentheses, and they launch a subshell

These {} are braces, and they are for grouping within the current shell. exit will exit your script.

Note the whitespace requirements are more stringent ({ needs to be followed by whitespace; } needs to be preceded by a semicolon plus whitespace, or a newline)

false || { echo foo; echo bar; }     # this is OK
false || {echo foo; echo bar}        # not OK

See Grouping Commands in the manual for the details.

glenn jackman
  • 27,524