使用'read'的多变量赋值在bash v4.3.48中有效,而在v4.4.7中无效 [英] Multiple variable assignment using 'read' works in bash v4.3.48 and does not in v4.4.7

查看:91
本文介绍了使用'read'的多变量赋值在bash v4.3.48中有效,而在v4.4.7中无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用两个发行版,分别使用bash v4.3.48和v4.4.7.

I'm using two distros which use bash v4.3.48 and v4.4.7.

read VAR1 VAR2 <<< $(echo 0 ; echo 1)
echo $VAR2

对于bash v4.3.48,以上命令的结果为$ VAR2,其值为1. 但是,对于bash 4.4.7,$ VAR2为空.

For bash v4.3.48, the result of commands above is $VAR2 has value 1. But, with bash 4.4.7, $VAR2 is null.

要获得相同的结果,在4.4.7中,我必须修改脚本:

To get the same result, in 4.4.7, I must modify the script:

read VAR1 VAR2 <<< $(echo -n $(echo 0 ; echo 1) )

我不知道我(以前的)脚本是错误的还是较新的bash有所更改.

I don't know my (previous) script was wrong or there're changes in the newer bash.

推荐答案

展开<<< $( )时的行为似乎有所变化.通常,当$( )出现时没有双引号时,结果将进行单词拆分和通配符扩展.但是,当它在<<<之后时,似乎bash的早期版本会跳过通配符扩展部分,但会对其进行单词拆分,然后将结果与空格一起粘贴回去.您可以使用cat而不是read来查看此内容:

It looks like the behavior when expanding <<< $( ) has changed slightly. Normally, when $( ) occurs without double-quotes around it, the result undergoes word splitting and wildcard expansion. But when it's after <<< it appears that early versions of bash skip the wildcard expansion part but do word-split it and then paste the result back together with spaces. You can see this by using cat instead of read:

$ echo $BASH_VERSION
4.2.10(1)-release
$ cat <<< $(echo 0; echo 1)
0 1
$ cat <<< $(echo '*       *'; echo 1)
* * 1

请注意,'* *'中的多余空格已消失,并且两个echo字符串之间的换行符已变为空格,但通配符并未扩展为文件列表.结果,当您使用read VAR1 VAR2 <<< $(echo 0 ; echo 1)时,read会收到"0 1"并将这些数字放入两个变量中.

Note that the extra spaces in '* *' have vanished, and the line breaks between the two echoed string have turned into spaces, but the wildcards didn't get expanded into a list of files. As a result, when you use read VAR1 VAR2 <<< $(echo 0 ; echo 1), read receives "0 1" and puts those digits in the two variables.

另一方面,bash的较新版本也跳过单词拆分:

On the other hand, newer versions of bash skip the word splitting as well:

$ echo $BASH_VERSION
4.4.12(1)-release
$ cat <<< $(echo 0; echo 1)
0
1
$ cat <<< $(echo '*       *'; echo 1)
*       *
1

这意味着,当您使用read VAR1 VAR2 <<< $(echo 0 ; echo 1)时,read命令会收到两行:"0"和"1",但它只读取一行("0"),并且因此只有$VAR1获得值.

That means that when you use read VAR1 VAR2 <<< $(echo 0 ; echo 1), the read command receives two lines: "0" and "1", but it only reads a single line ("0") and so only $VAR1 gets a value.

更新: Eric Renouf 发行说明中发现了更改对于bash-4.4-beta :

z. Bash不再拆分here-strings的扩展,因为 文件资料 一直说.

z. Bash no longer splits the expansion of here-strings, as the documentation has always said.

这篇关于使用'read'的多变量赋值在bash v4.3.48中有效,而在v4.4.7中无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆