Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access element of $* (or $@) by index

Tags:

bash

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
like image 607
Andrei Avatar asked May 03 '11 19:05

Andrei


2 Answers

$* 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
like image 160
Jay Adkisson Avatar answered Oct 02 '22 08:10

Jay Adkisson


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

like image 33
sehe Avatar answered Oct 02 '22 10:10

sehe