4

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!

7

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
  • Perfect! That works. I tried that with single quotes and it didn't work, but double quotes works! – Aidan Jul 28 '16 at 19:20
  • @Aidan Where did you put single/double quotes to make it work/not work? – Kusalananda Jul 28 '16 at 20:18
  • FWIW, with single quotes lists=('${@}') would return the single element literal ${@} and with no quotes lists=(${@}) would have expanded the input to a length of 5. – Stephen Harris Jul 28 '16 at 20:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.