How to get bash indexes of parameters array?
5,022
Solution 1
You can calculate from the number of arguments:
seq ${#@}
Solution 2
For the record, in zsh
, the indexOf functionality is with:
$ set foo bar baz bar foo
$ echo $@[(i)bar] $@[(I)bar]
2 4
($2
is the first match (using the i
subscript flag), $4
the last match (I
subscript flag)).
Solution 3
You don't need a dummy array. You can use a counter variable:
indexof() {
search="$1"; shift
i=0
for arg; do
[ "$search" = "$arg" ] && return $i
((i++))
done
return -1
}
Note that for arg; do
uses "$@"
by default, that's why in "$@"
can be omitted.
Related videos on Youtube
Author by
MetNP
Updated on September 18, 2022Comments
-
MetNP almost 2 years
I want indexes of parameters,
and can get it by dummy var:
dummy=( $@ ) echo ${!dummy[@]}
but is there straight way to get them, something like
$!@ ... not working $!* ... not working
... or something like that?
NOTE: original function that i want to have without arr var is this:
function indexof() { search="$1"; shift; arr=( $@ ) for i in "${!arr[@]}"; do [ "$search" == "${arr[$i]}" ] && return $i; done return -1 }
-
dave_thompson_085 over 7 yearsNote that
arr=( $@ )
will split args that contain IFS (by default whitespace); if you didn't dis-want this form entirely you would wantarr=( "$@" )
-
MetNP over 7 years@dave_thompson_085 , yes, but this is first time that i see that parrametters array is not as other arrays (no syntax for getting indexes), or maybe indexes was meant for associative arrays initialy.
-
-
MetNP over 7 yearsnice, how to tell seq to go 0..n-1 instead 1..n like original code do
-
Ipor Sircer over 7 yearsit's very hard:
seq 0 $((${#@}-1))
-
Kusalananda over 5 years
$#
would be better.