1

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
}
| improve this question | | | | |
  • 1
    Note that arr=( $@ ) will split args that contain IFS (by default whitespace); if you didn't dis-want this form entirely you would want arr=( "$@" ) – dave_thompson_085 Dec 22 '16 at 9:14
  • @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 Dec 22 '16 at 12:08
1

You can calculate from the number of arguments:

seq ${#@}
| improve this answer | | | | |
  • nice, how to tell seq to go 0..n-1 instead 1..n like original code do – MetNP Dec 22 '16 at 2:25
  • it's very hard: seq 0 $((${#@}-1)) – Ipor Sircer Dec 22 '16 at 2:26
  • ok, so if there is no direct bash way like $!@... seq seems better than dummy var, marking this as answer. – MetNP Dec 22 '16 at 2:34
  • $# would be better. – Kusalananda Jan 29 '19 at 18:16
1

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.

| improve this answer | | | | |
1

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)).

| improve this answer | | | | |
0

You can instead use the 'arithmetic-for' form:

indexof(){ search=$1; shift 
    for(( i=1; i<=$#; i++ )); do [[ $search == ${!i} ]] && return $i; done
    return -1 # as an old LISPer I'd prefer 0 for the notfound case
}

Not particularly better (IMO) but different.

| improve this answer | | | | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.