I have something in bash
like
myArray=(\'red\' \'orange\' \'green\')
And I would like to do something like
echo ${
A little more concise and works in Bash 3.x:
my_array=(red orange green)
value='green'
for i in "${!my_array[@]}"; do
[[ "${my_array[$i]}" = "${value}" ]] && break
done
echo $i
I like that solution:
let "n=(`echo ${myArray[@]} | tr -s " " "\n" | grep -n "green" | cut -d":" -f 1`)-1"
The variable n will contain the result!
This outputs the 0-based array index of the query (here "orange").
echo $(( $(printf "%s\n" "${myArray[@]}" | sed -n '/^orange$/{=;q}') - 1 ))
If the query does not occur in the array then the above outputs -1
.
If the query occurs multiple times in the array then the above outputs the index of the query's first occurrence.
Since this solution invokes sed, I doubt that it can compete with some of the pure bash solutions in this thread in efficiency.