bash – 花括号和管道中的分组命令不保留变量

假设我在当前工作目录中有一个文件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.但它没有发生.为什么?

这不是导致子壳创建的花括号,而是管道.

为了证明这一点:

${ ls && v=3; } > tmp
$echo "$v"
3

引用Greg

In most shells,each command of a pipeline is executed in a separate SubShell.

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...