Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash Select position of array element by args

Tags:

bash

I want make a bash script which returns the position of an element from an array by give an arg. See code below, I use:

#!/bin/bash
args=("$@")
echo ${args[0]}
test_array=('AA' 'BB' 'CC' 'DD' 'EE')
echo $test_array
elem_array=${#test_array[@]}
for args in $test_array
do
        echo 
done

Finally I should have output like:

$script.sh DD
4
like image 238
Cătălin George Feștilă Avatar asked Oct 30 '25 02:10

Cătălin George Feștilă


1 Answers

#!/bin/bash

A=(AA BB CC DD EE)

for i in "${!A[@]}"; do
        if [[ "${A[i]}" = "$1" ]]; then
                echo "$i"
        fi
done

Note the "${!A[@]}" notation that gives the list of valid indexes in the array. In general you cannot just go from 0 to "${#A[@]}" - 1, because the indexes are not necessarily contiguous. There can be gaps in the index range if there were gaps in the array element assignments or if some elements have been unset.

The script above will output all indexes of the array for which its content is equal to the first command line argument of the script.

EDIT:

In your question, you seem to want the result as a one-based array index. In that case you can just increment the result by one:

#!/bin/bash

A=(AA BB CC DD EE)

for i in "${!A[@]}"; do
        if [[ "${A[i]}" = "$1" ]]; then
                let i++;

                echo "$i"
        fi
done

Keep in mind, though, that this index will have to be decremented before being used with a zero-based array.

like image 148
thkala Avatar answered Nov 01 '25 18:11

thkala