加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 01:36:30 所属栏目:安全 来源:网络整理
导读:假设我在当前工作目录中有一个文件myfile.如果命令正常执行,我想设置变量,但也使用其结果. $ls myfile v=3myfile$echo "$v"3 但现在我也想管道结果,所以我使用{list;用于对命令进行分组的语法: $unset v${ ls myfile v=3; } | grep myfmyfile$echo "$v" # v
假设我在当前工作目录中有一个文件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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读