Search an array return index in bash

Just pesuocode, but this is essentially what I would like to do.

Array=("1" "Linux" "Test system" "2" "Windows" "Workstation" "3" "Windows" "Workstation") echo "number " ${array[search "$1"]} "is a" ${array[search "$1" +1]} ${array[search "$1" +2])} 

Is this possible with bash? I could find information only on search and replace. I have not seen anything. It came back and indexed.

+4
source share
2 answers

Something like this should work:

 search() { local i=1; for str in "${array[@]}"; do if [ "$str" = "$1" ]; then echo $i return else ((i++)) fi done echo "-1" } 

Despite the fact that cyclic movement through the array to search for the index is certainly possible, this alternative solution with an associative array is more practical:

 array=([1,os]="Linux" [1,type]="Test System" [2,os]="Windows" [2,type]="Work Station" [3,os]="Windows" [3,type]="Work Station") echo "number $1 is a ${array[$1,os]} ${array[$1,type]}" 
+5
source

You can modify this example from this link to return the index without any problems:

 # Check if a value exists in an array # @param $1 mixed Needle # @param $2 array Haystack # @return Success (0) if value exists, Failure (1) otherwise # Usage: in_array "$needle" "${haystack[@]}" # See: http://fvue.nl/wiki/Bash:_Check_if_array_element_exists in_array() { local hay needle=$1 shift for hay; do [[ $hay == $needle ]] && return 0 done return 1 } 
+4
source

Source: https://habr.com/ru/post/1393049/


All Articles