1

How can I pass an array where some values have spaces. I mean:

script.sh

#/bin/bash
echo $1, $#

I can run this little script

$ ./script.sh a --> a, 1
$ ./script.sh "a b" --> a b, 1
$ v=("a b" c)
$ ./script.sh ${v[@]} --> a, 3
$ ./script.sh ${v[@]@Q} --> 'a, 3

I would like to print "a b, 2" without changing the script Is it possible?

The only way I have found to achive it is:

eval "./script.sh ${v[@]@Q}" --> a b, 2

Is there a smarter way?

user721730
  • 438
  • 1
  • 7
  • 11
  • 1
    Like that `./script.sh "${v[0]}"`? – Arkadiusz Drabczyk Nov 28 '19 at 18:59
  • Thanks. In this case I would be right but I want to use all the values in the array. I'm going to rewrite the example – user721730 Nov 28 '19 at 19:10
  • `"${array[@]}"` expands to all values in an array. So, `./script "${v[@]}"` -- no `eval` needed. – Charles Duffy Nov 28 '19 at 19:19
  • Note that **the quotes are not optional**; `${array[@]}` does something subtly different (identical to unquoted `${array[*]}`, which is to say, combining all array elements with the first character in IFS, then word-splitting the result and glob-expanding each resulting word). – Charles Duffy Nov 28 '19 at 19:20
  • ...I closed with a duplicate that speaks about "functions" in its title, but the answer is fully applicable to external/regular commands as well. – Charles Duffy Nov 28 '19 at 19:21
  • Charles, that's it. I have spend several hours trying everything but "${array[@]}". Thanks – user721730 Nov 28 '19 at 22:11

0 Answers0