Reputation: 14485
Imagine the code:
ls || echo "Unable to execute ls (returned non zero)"
What if I needed to execute more commands like:
ls || echo "this is echo 1" <some operator> echo "this is echo 2" <some operator> exit 1
in C (assumming I have a function ls
) I could do (even if it looks insane):
ls() || (command1() && command2());
but I doubt I can use parentheses like this in bash.
I know I can create a Bash function that would contain these commands, but what if I needed to combine this with exit 1
(exit in a function would exit that function, not whole script)?
Upvotes: 36
Views: 13367
Reputation: 241868
In fact, you can use parentheses. They just tell bash "run the commands in a subshell". You can also use curlies:
ls || { echo 1 ; echo 2 ; }
Note that ;
or a newline before the closing curlie is not optional.
Upvotes: 19
Reputation: 123508
You can group multiple commands within { }
. Saying:
some_command || { command1; command2; }
would execute command1
and command2
if some_command
exited with a non-zero return code.
{}
{ list; }
Placing a list of commands between curly braces causes the list to be executed in the current shell context. No subshell is created. The semicolon (or newline) following list is required.
Upvotes: 62