Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the right way to do command grouping in bash

Tags:

bash

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?

like image 590
Elad Weiss Avatar asked Sep 07 '17 09:09

Elad Weiss


People also ask

How do you group commands in shell script?

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.

What does [- Z $1 mean in Bash?

$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.

What is command grouping and how does it work?

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.


1 Answers

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; };.

like image 117
campovski Avatar answered Oct 09 '22 16:10

campovski