What is the right way to do command grouping in bash

前端 未结 1 1048
野的像风
野的像风 2021-01-03 03:48

I would like to group few bash instructions after a condition:

First attempt:

$ [[ 0 == 1 ]] && echo 1; echo 2
2

Second att

相关标签:
1条回答
  • 2021-01-03 04:21

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

    0 讨论(0)
提交回复
热议问题