Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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!

share|improve this question
1  
Don't forget to accept (with the checkmark) any answer that solves your problem! – Jeff Schaller Jul 28 at 19:52

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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