0

I do a lot of scripting in Bash, and instead of using the typical syntax:

if [[ condition ]]
then 
    foo
    bar
else 
    baz
    quux
fi

I often use a simplified version of it:

[[ condition ]] && ( foo; bar ) || ( baz; quux )

However, looking at some scripts at the new company I'm working at, I noticed that in place of the regular parenthesis, it works just fine using the curly brackets. For example:

$ false && ( echo -n "Hello "; echo "World"; ) || ( echo -n "Goodbye "; echo "World";  )
Goodbye World
$ true && ( echo -n "Hello "; echo "World"; ) || ( echo -n "Goodbye "; echo "World";  )
Hello World
$ false && { echo -n "Hello "; echo "World"; } || { echo -n "Goodbye "; echo "World";  }
Goodbye World
$ true && { echo -n "Hello "; echo "World"; } || { echo -n "Goodbye "; echo "World";  }
Hello World

So the first two examples use parenthesis, which is what I usually use. The last two use curly brackets.

So my question is... whats the difference? When should I use one and not the other?

Thanks!

Justin
  • 1,959
  • 5
  • 22
  • 40
  • Your simplification is not equivalent to the original `if` statement. If `condition` is true and `bar` has a non-zero exit status, `(baz; quux)` will still execute. Try `true && false || echo oops`. – chepner Jul 01 '16 at 15:47
  • @chepner: as an impartial 3rd party, I've just read the entire alleged duplicate question and answers, ([How to use double or single bracket, parentheses, curly braces](http://stackoverflow.com/questions/2188199/how-to-use-double-or-single-bracket-parentheses-curly-braces)), which is a discussion of arithmetic, functional, and logical bashisms, but it doesn't generally address command grouping via subshells vs. current shells, (the current question). The duplication flag is therefore incorrect. – agc Jul 01 '16 at 17:39
  • [One of the answers](http://stackoverflow.com/a/2188223/1126841) does. – chepner Jul 01 '16 at 18:12
  • @chepner, #3 & #4b of *Carl Norum*'s answer doesn't sufficiently compare and contrast the the two methods of command grouping. [That whole question](http://stackoverflow.com/questions/2188199/how-to-use-double-or-single-bracket-parentheses-curly-braces/2188223#2188223) is more of a competition to list every possible *bash* usage of '(){}[]', and comes across as a somewhat random survey and miscellany. This current question is focused on *command grouping* only, which is a distinct and practical subtopic in of itself. – agc Jul 01 '16 at 18:45
  • @chepner, also please include `@agc` next time, or I might not see your reply; thanks. – agc Jul 01 '16 at 18:51

0 Answers0