微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐