为什么bash数组在这一行上错误地进行了分割?

huangapple go评论58阅读模式
英文:

Why is bash array-splitting this line incorrectly?

问题

在下面的示例中,为什么"[1]"和"[20]"可以正常拆分,但"[10000]"不能呢?

看起来它将10000转换为1并丢弃括号?

#!/bin/bash

var="[ 1]"
vararray=($var)
echo "var=${var}"
echo "vararray[0]=${vararray[0]}"

var="[20]"
vararray=($var)
echo "var=${var}"
echo "vararray[0]=${vararray[0]}"

var="[10000]"
vararray=($var)
echo "var=${var}"
echo "vararray[0]=${vararray[0]}"

结果...

$ ./bashtest.sh
var=[ 1]
vararray[0]=[ 1]
var=[20]
vararray[0]=[20]
var=[10000]
vararray[0]=1 << 为什么?
英文:

In the below example, why do "[ 1]" and "[20]" split fine, but "[10000]" does not?

It appears to be converting the 10000 to 1 and dropping the brackets?

#!/bin/bash

var=&quot;[ 1]&quot;
vararray=($var)
echo &quot;var=${var}&quot;
echo &quot;vararray[0]=${vararray[0]}&quot;

var=&quot;[20]&quot;
vararray=($var)
echo &quot;var=${var}&quot;
echo &quot;vararray[0]=${vararray[0]}&quot;

var=&quot;[10000]&quot;
vararray=($var)
echo &quot;var=${var}&quot;
echo &quot;vararray[0]=${vararray[0]}&quot;

Results...

$ ./bashtest.sh
var=[ 1]
ararray[0]=[
var=[20]
vararray[0]=[20]
var=[10000]
vararray[0]=1 &lt;&lt; what?

答案1

得分: 4

在当前目录中有一个名为1的文件。这通常是无意中发生的,例如,如果有人想要运行2&gt;&amp;1,但错误地运行了2&gt;1

[20]不会匹配到1,它只会匹配到2或0。

[ 1],在默认IFS值下运行时,会被拆分成[1],但这两者都不是有效的通配符,因此在不引用的情况下扩展它不会执行任何通配符操作。

但是,[10000],就像[01]一样,如果存在以这些名称之一命名的文件,它将匹配到0或1。在你的示例场景中,你显然有一个名为1的文件在你的当前工作目录中。


不要使用未引用的扩展来将字符串拆分成数组。

相反,使用read -r -a vararray <<< "$var",在明确设置IFS以包含您要拆分的字符之后,是一个更好的选择。

英文:

Presume that you have a file named 1 in your current directory. (This often happens unintentionally, f/e if someone wants to run 2&gt;&amp;1 but runs 2&gt;1 instead by mistake).

[20] does not glob to 1 -- it globs only to 2 or 0.

[ 1], when run with the default IFS value, is word-split into [ and 1], neither of which is a valid glob, so expanding it unquoted doesn't perform any globbing operation at all.

However, [10000] -- just like [01] -- will glob to either 0 or 1, if a file by any of those names exists. In your example scenario, you clearly had a file named 1 in your current working directory.


Don't use unquoted expansion to split strings into arrays.

Instead, use read -r -a vararray &lt;&lt;&lt;&quot;$var&quot;, optionally after explicitly setting IFS to contain only the characters you want to split on.

huangapple
  • 本文由 发表于 2023年2月16日 08:49:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75466805.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定