在bash中进行命令分组的正确方法是什么 [英] What is the right way to do command grouping in bash
问题描述
我想在条件之后对一些bash指令进行分组:
I would like to group few bash instructions after a condition:
第一次尝试:
$ [[ 0 == 1 ]] && echo 1; echo 2
2
第二次尝试:
$ [[ 0 == 1 ]] && (echo 1; echo 2)
$ [[ 0 == 0 ]] && (echo 1; echo 2)
1
2
所以后者就是我想要的.
So the latter is what I want.
问题:这是我第一次在bash中使用(
... )
语法. (
... )
是正确的方法吗,还是有一些我可能会缺少的副作用?
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?
推荐答案
放置()
中的命令创建一个子外壳,在该子外壳中执行分组的命令.这意味着,例如,在subshell中对变量所做的任何更改都将保留在subshell中
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
还请注意{}
和分号内部的空格:{ ((n++)); echo $n; };
.
Also mind the spaces on the inside of {}
and semicolons: { ((n++)); echo $n; };
.
这篇关于在bash中进行命令分组的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!