英文:
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="[ 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]}"
Results...
$ ./bashtest.sh
var=[ 1]
ararray[0]=[
var=[20]
vararray[0]=[20]
var=[10000]
vararray[0]=1 << what?
答案1
得分: 4
在当前目录中有一个名为1
的文件。这通常是无意中发生的,例如,如果有人想要运行2>&1
,但错误地运行了2>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>&1
but runs 2>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 <<<"$var"
, optionally after explicitly setting IFS to contain only the characters you want to split on.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论