5

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!

0

    1 Answer 1

    8

    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 
    3
    • Perfect! That works. I tried that with single quotes and it didn't work, but double quotes works!
      – Aidan
      CommentedJul 28, 2016 at 19:20
    • @Aidan Where did you put single/double quotes to make it work/not work?
      – Kusalananda
      CommentedJul 28, 2016 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.CommentedJul 28, 2016 at 20:21

    You must log in to answer this question.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.