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?
$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.
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.
To access elements of array using index in Bash, use index notation on the array variable as array[index].
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With