Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the index of a value in a Bash array

I have something in bash like

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

And I would like to do something like

echo ${myArray['green']} 

Which in this case would output 2. Is this achievable?

like image 591
user137369 Avatar asked Feb 22 '13 16:02

user137369


People also ask

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script.

How do you find the index of an array?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.

How do I index an array in bash?

To access elements of array using index in Bash, use index notation on the array variable as array[index].

How do I find an element in an array in Linux?

To find the index of specified element in an array in Bash, use For loop to iterate over the index of this array. In the for loop body, check if the current element is equal to the specified element. If there is a match, we may break the For loop and we have found index of first occurrence of specified element.


1 Answers

This will do it:

#!/bin/bash  my_array=(red orange green) value='green'  for i in "${!my_array[@]}"; do    if [[ "${my_array[$i]}" = "${value}" ]]; then        echo "${i}";    fi done 

Obviously, if you turn this into a function (e.g. get_index() ) - you can make it generic

like image 131
Steve Walsh Avatar answered Oct 22 '22 20:10

Steve Walsh