Access element $ * (or $ @) by index

How to access an element of an array $ * (or $ @) by index?
For example, take a 3-element array and index = 1:

a=( abc ) set -- abc echo ${a[1]} b # good echo ${*[1]} bash: ... bad substitution echo ${@[1]} bash: ... bad substitution 
+8
bash
source share
4 answers

BUT

you can assign to another array and have fun

 function test { declare -av=("$@") 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

+4
source share

$* and $@ are not arrays, but spatial separation variables defined by a function or script of the call time. You can access your 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 
+9
source share

For arguments, you need to shift it like this:

 while (( "$#" )); do # $1 contains the next argument shift done 
+3
source share

I redirect my answer here:


Indirectly use the command line argument

 argnum=3 # You want to get the 3rd arg do-something ${!argnum} # Do something with the 3rd arg 

Example:

 argc=$# for (( argn=1; argn<=argc; argn++)); do if [[ ${!argn} == "foo" ]]; then echo "Argument $argn of $argc is 'foo'" fi done 
+2
source share

All Articles