0

I am writing a bash script that generates a list of arguments to pass to another, external script. This list of arguments can contain strings with spaces in it. Note that this list of arguments will be of varying length depending on how the script is run.

The bash script looks like this:

#!/bin/bash
# script1.sh

... some code that populates the array ARGS_TO_PASS ...

# NOTE! ARGS_TO_PASS can be of varying length depending on what the above code does.
#
# Here is example of what ARGS_TO_PASS might be:
# ARGS_TO_PASS=(a b c 'the quick brown fox')

# Now, call script2.sh on ARGS_TO_PASS.
script2.sh ${ARGS_TO_PASS[*]}

Here is the second script:

#!/bin/bash
# script2.sh
while [[ $# -gt 0 ]]; do
    echo "parsing arg: $1"
    shift
done

If the last line of script1.sh is script2.sh ${ARGS_TO_PASS[*]} the output looks like this:

parsing arg: a
parsing arg: b
parsing arg: c
parsing arg: the
parsing arg: quick
parsing arg: brown
parsing arg: fox

If the last line of script1.sh is script2.sh "${ARGS_TO_PASS[*]}" the output looks like this:

parsing arg: a b c 'the quick brown fox'

Neither of those are what I want. What I want is the output to look like this:

parsing arg: a
parsing arg: b
parsing arg: c
parsing arg: the quick brown fox

Is there any way to do this?

rlandster
  • 7,294
  • 14
  • 58
  • 96

1 Answers1

1

You can use

script2.sh "${ARGS_TO_PASS[@]}"
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
  • @rlandster See my explanation [here](https://stackoverflow.com/questions/3811345/how-to-pass-all-arguments-passed-to-my-bash-script-to-a-function-of-mine/3816747#3816747) (about `$@`, not an array, but it works the same). – Gordon Davisson Apr 24 '21 at 04:39
  • 1
    "If the subscript is ‘@’ or ‘*’, the word expands to all members of the array name. These subscripts differ only when the word appears within double quotes. If the word is double-quoted, ${name[*]} expands to a single word with the value of each array member separated by the first character of the IFS variable, and ${name[@]} expands each element of name to a separate word." – Diego Torres Milano Apr 24 '21 at 04:40
  • 1
    Basic parameter expansion for an array using `"${array[@]}"` expands the array with elements quoted, so if they contain whitespace, the elements are preserved and no word-splitting occurs. – David C. Rankin Apr 24 '21 at 04:40
  • https://www.gnu.org/software/bash/manual/html_node/Arrays.html – Diego Torres Milano Apr 24 '21 at 04:40