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.

Share:
5,022

Related videos on Youtube

MetNP
Author by

MetNP

Updated on September 18, 2022

Comments

  • MetNP
    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
      dave_thompson_085 over 7 years
      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=( "$@" )
    • MetNP
      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
    MetNP over 7 years
    nice, how to tell seq to go 0..n-1 instead 1..n like original code do
  • Ipor Sircer
    Ipor Sircer over 7 years
    it's very hard: seq 0 $((${#@}-1))
  • Kusalananda
    Kusalananda over 5 years
    $# would be better.