'read -ra' vs direct assign
In a bash (version 3) script, I want to store the passed command line arguments so that I can iterate over them multiple times (with a shift) and potentially strip some of them.
From what I understand, it "$@"
looks like an array in the first place.
My first impulse is to write: cmdArgs="$@"
and then manipulate cmdArgs
like any other array.
However, I read a lot of answers that use a different syntax: read -ra cmdArgs <<<"$@"
Why? The second option is longer, less obvious in what it does, but appears to be the preferred choice. So why?
source to share
Wrong. Both try to use it correctly "$@"
, but each uses it in context, where the resulting wordlist collapses into a single space-separated string before you can access the individual elements.
The first one assigns the string to the correct variable, not an array.
$ set "foo bar" baz
$ cmdArgs="$@"
$ printf "%s\n" "$cmdArgs"
foo bar baz
The second uses an operator <<<
that only takes one word, so it read
takes a single space-separated string and splits it into a separated list, so that the argument containing spaces is split into multiple array elements.
$ read -ra cmdArgs <<< "$@"
$ printf "%s\n" "${cmdArgs[@]}"
foo
bar
baz
The correct method
$ cmdArgs=( "$@" )
$ printf "%s\n" "${cmdArgs[@]}"
foo bar
baz
source to share