Get the index of a value in a Bash array

后端 未结 15 526
说谎
说谎 2021-01-30 03:41

I have something in bash like

myArray=(\'red\' \'orange\' \'green\')

And I would like to do something like

echo ${         


        
15条回答
  •  星月不相逢
    2021-01-30 04:34

    This is just another way to initialize an associative array as chepner showed. Don't forget that you need to explicitly declare or typset an associative array with -A attribute.

    i=0; declare -A myArray=( [red]=$((i++)) [orange]=$((i++)) [green]=$((i++)) )
    echo ${myArray[green]}
    2
    

    This removes the need to hard code values and makes it unlikely you will end up with duplicates.

    If you have lots of values to add it may help to put them on separate lines.

    i=0; declare -A myArray; 
    myArray+=( [red]=$((i++)) )
    myArray+=( [orange]=$((i++)) )
    myArray+=( [green]=$((i++)) )
    echo ${myArray[green]}
    2
    

    Say you want an array of numbers and lowercase letters (eg: for a menu selection) you can also do something like this.

    declare -a mKeys_1=( {{0..9},{a..z}} );
    i=0; declare -A mKeys_1_Lookup; eval mKeys_1_Lookup[{{0..9},{a..z}}]="$((i++))";
    

    If you then run

    echo "${mKeys_1[15]}"
    f
    echo "${mKeys_1_Lookup[f]}"
    15
    

提交回复
热议问题