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!

2
  • Is removing the parentheses not enough for you? I know it's not proper arithmetic logic, but it will evaluate across in order, and should achieve what I think it is supposed to.
    – Wally
    Commented Jan 16, 2014 at 18:58
  • @Wally - yes, in that specific example it would fit, but I really would like to know, how to prioritize expressions (in general) without creating sub-shells. Commented Jan 16, 2014 at 19:03

1 Answer 1

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.

2
  • 1
    } needs to be preceded by a command separator, regardless of whether it's a newline, semicolon, or ampersand. Commented Jan 16, 2014 at 19:51
  • Thank you, it works! I even skimmed over the topic of "grouping in BASH" some time ago, but didn't associated it with evaluation priority. Commented Jan 20, 2014 at 15:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .