假设我在当前工作目录中有一个文件myfile.如果命令正常执行,我想设置变量,但也使用其结果.
$ls myfile && v=3 myfile $echo "$v" 3
但现在我也想管道结果,所以我使用{list;用于对命令进行分组的语法:
$unset v ${ ls myfile && v=3; } | grep myf myfile $echo "$v" # v is not set
Bash reference manual -> 3.2.4.3 Grouping Commands说:
06002
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.
所以,根据我的理解,v应该设置为3.但它没有发生.为什么?
这不是导致子壳创建的花括号,而是管道.
原文链接:https://www.f2er.com/bash/383492.html为了证明这一点:
${ ls && v=3; } > tmp $echo "$v" 3
引用Greg:
In most shells,each command of a pipeline is executed in a separate SubShell.