bash 脚本中的数组长度问题

Aid*_*dan 4 bash array

我正在编写一个脚本,将一些命令行参数存储为一个数组,稍后使用该数组,但我在获取脚本中数组的正确长度时遇到了问题。

在终端中,使用 bash,我尝试了这个:

$:>array=( 1 2 3 4 ) $:>echo array = ${array[*]} and length = ${#array[*]}

echo 的输出是:

array = 1 2 3 4 and length = 4

哪个工作正常。我简化了我遇到问题的脚本,该脚本应该做完全相同的事情,但我得到的数组长度为 1。脚本如下..

#!/bin/bash list=${@} echo array = ${list[*]} and length = ${#list[*]}

如果我从终端调用脚本

$:>./script.sh ${test[*]}

输出是

array = 1 2 3 4 and length = 1

我尝试了几种不同的方法来保存数组并将其打印出来,但我不知道如何解决这个问题。任何解决方案将不胜感激!

Ste*_*ris 8

您将输入扁平化为单个值。

你应该做

list=("${@}")
Run Code Online (Sandbox Code Playgroud)

维护数组和参数中空格的潜力。

如果您错过了"那么类似的东西./script.sh "a b" 2 3 4将返回长度为 5,因为第一个参数将被拆分。随着"我们得到

$ cat x
#!/bin/bash
list=("${@}")

echo array = ${list[*]} and length = ${#list[*]}

$ ./x "a b" 2 3 4  
array = a b 2 3 4 and length = 4
Run Code Online (Sandbox Code Playgroud)