I would like to group few bash instructions after a condition:
First attempt:
$ [[ 0 == 1 ]] && echo 1; echo 2
2
Second attempt:
$ [[ 0 == 1 ]] && (echo 1; echo 2)
$ [[ 0 == 0 ]] && (echo 1; echo 2)
1
2
So the latter is what I want.
Question: This is the 1st time I'm using (
...)
syntax in bash. Is (
...)
the right way to go, or does it have some side effects I might be missing?
Group commands in the current shell: { } 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.
$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.
The GROUP command allows you to execute several commands on a record before moving to the next record in the table, which can significantly reduce processing time. You can use the LOOP command inside the GROUP command if you need to execute a series of commands more than once against a record.
Placing commands in ()
creates a subshell in which the grouped commands are executed. That means that any changes to variables made in subshell, stay in subshell, for example
$ n=5; [[ "$n" == "5" ]] && ( ((n++)); echo $n); echo $n
6
5
Instead you want to group with {}
which doesn't invoke a subshell. Then the output would be
$ n=5; [[ "$n" == "5" ]] && { ((n++)); echo $n; }; echo $n
6
6
Also mind the spaces on the inside of {}
and semicolons: { ((n++)); echo $n; };
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With