Arrays 如何在Debian Jessie的bash脚本中使用数组?
当我尝试执行以下命令时Arrays 如何在Debian Jessie的bash脚本中使用数组?,arrays,linux,bash,shell,Arrays,Linux,Bash,Shell,当我尝试执行以下命令时 #!/bin/sh folders=("/usr/include") for i in ${folders[@]}; do echo ${i} done exit 0 我得到test.sh:3:test.sh:语法错误:“(“意外的”。我也尝试过使用#!/bin/bash,但也不起作用。我在Debian Jessie的脚本中尝试了这一点,它产生了上述错误。同样的脚本在Ubuntu 14.04上运行良好 另外我也试过了 # foo=(/usr/inclu
#!/bin/sh
folders=("/usr/include")
for i in ${folders[@]}; do
echo ${i}
done
exit 0
我得到test.sh:3:test.sh:语法错误:“(“意外的”
。我也尝试过使用#!/bin/bash
,但也不起作用。我在Debian Jessie的脚本中尝试了这一点,它产生了上述错误。同样的脚本在Ubuntu 14.04上运行良好
另外我也试过了
# foo=(/usr/include); echo $foo
/usr/include
这很有效。
我还用cat-e test.sh
#!/bin/sh$
$
folders=("/usr/include")$
for i in ${folders[@]}; do$
echo ${i}$
done$
exit 0$
编辑
我以
sh./test.sh
的形式执行脚本,使用bash
,您应该使用declare-a
:
#!/bin/sh$
$
folders=("/usr/include")$
for i in ${folders[@]}; do$
echo ${i}$
done$
exit 0$
#!/bin/bash
declare -a folders=("/usr/include");
for i in ${folders[@]}; do
echo ${i}
done
exit 0
使用
bash
,您应该使用declare-a
:
#!/bin/bash
declare -a folders=("/usr/include");
for i in ${folders[@]}; do
echo ${i}
done
exit 0
/bin/sh
不是Bash,没有数组;你必须使用/bin/Bash
,正如我刚才看到的,你说你使用了…嗯。你怎么调用脚本呢?我使用了sh./test.sh
。我刚刚使用了chmod+x test.sh&./test.sh
,它似乎与#!/bin/Bash
一起工作。是的,sh./test.sh
将运行它使用的是dash
,它比bash更严格地说是POSIX。请参见。另外,它对POSIX shell中的数组有一些想法。是的,如果您称它为sh./test.sh
,它与hashbang行中的内容无关。它也与bash./test.sh
,与hashbang行中的内容无关。/bin/sh
不是Bash,也没有数组;您必须使用/bin/Bash
,正如我刚才看到的,您说您使用了…嗯。您如何调用脚本?我使用了sh./test.sh
。我只使用了chmod+x test.sh&./test.sh
,它似乎与一起工作!/bin/Bash
。是的,sh test.sh
将与破折号一起运行它
,它比bash更严格地说是POSIX。请参见。另外,它对POSIX shell中的数组有一些想法。是的-如果您称它为sh./test.sh
,它与hashbang行中的内容无关。它也与bash./test.sh
,而与hashbang行中的内容无关。虽然这个答案可能没有错,但是使用正确的调用约定bash./test.sh
解决了问题。我想如果我使用sh./test.sh
调用您的脚本,问题将保持不变。当然,您是对的,此语法对sh
无效,但OP问题是针对bash
的。是的,对不起,我没有注意到问题已经存在ady已解决。好的,我现在明白了,它是用sh
调用的。您可以使用declare-a
来声明数组,但这不是必需的。使用数组赋值语法a=(…)
自动设置名称的数组属性。虽然这个答案可能没有错,但问题是通过使用正确的调用约定bash./test.sh
解决的。我想如果我使用sh./test.sh
调用脚本,问题将保持不变。当然,您是对的,此语法对sh
无效,但是OP问题是针对bash
。是的,对不起,我没有注意到问题已经解决。好的,我现在明白了,它是用sh
调用的。您可以使用declare-a
来声明数组,但这不是必需的。使用数组赋值语法a=(…)
自动设置名称的数组属性。