How do I access eleent of $* array (or $@) by index ?
For example, let's take 3-element array and index=1:
a=( a b c )
set -- a b c
echo ${a[1]}
b # good
echo ${*[1]}
bash: ... bad substitution
echo ${@[1]}
bash: ... bad substitution
$*
and $@
are not arrays, but rather space-delimited context variables determined at function or script call time. You can access their elements with $n
, where n is the position of the argument you want.
foo() {
echo $1
}
foo one two three # => one
foo "one two" three # => one two
BUT
you can assign to another array and have fun
function test
{
declare -a v=("$@")
for a in "${v[@]}"; do echo "'$a'"; done
}
$ test aap noot mies
'aap'
'noot'
'mies'
$ test aap noot mies\ broer
'aap'
'noot'
'mies broer'
Obviously this allows you to access by index ${v[7]}
since it is just a regular array
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With