Bash – Issue with array length in bash script

arraybash

I am writing a script that stores some of the command line arguments as an array, and uses the array later, but I'm having an issues getting the correct length of the array in the script.

In the terminal, using bash, I tried this:

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

and the output from echo is:

array = 1 2 3 4 and length = 4

Which is working correctly.
I simplified the script that I was having an issue with, and the script is supposed to do the exact same thing, but I get an array length of 1. The script is as follows..

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

And if I call the script from the terminal with

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

the output is

array = 1 2 3 4 and length = 1

I've tried a few different way of saving the array, and printing it out, but I can't figure out how to fix this issue. Any solutions would be appreciated!

Best Answer

You're flattening the input into a single value.

You should do

list=("${@}")

to maintain the array and the potential of whitespace in arguments.

If you miss out the " then something like ./script.sh "a b" 2 3 4 will return a length of 5 because the first argument will be split up. With " we get

$ 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
Related Question