4

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 only find info on search and replace. I didn't see anything That would return and index.

choroba
  • 231,213
  • 25
  • 204
  • 289
matt
  • 145
  • 1
  • 1
  • 4

2 Answers2

5

Something like that should work:

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

While looping over the array to find 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]}"
user123444555621
  • 148,182
  • 27
  • 114
  • 126
4

You could modify this example from this link to return an index without much trouble:

# 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
}
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
  • -1 for the link returning 403 and the answer being totally "obscure" – Sorin Jan 25 '12 at 22:21
  • 1
    @Sorin I'm not getting a 403 with that link. – Dan Fego Jan 25 '12 at 22:49
  • @Dan Fego: I would attach a screenshot if I could. However, the answer is still totally obscure, and lacking even the basic information. – Sorin Jan 25 '12 at 22:55
  • You're probably right. But the OP should try something (like a simple internet search) before asking, too. – Carl Norum Jan 25 '12 at 23:17
  • @Carl Norum: actually, it took me a while to figure it out. Anyway, removed the down vote, since the now it has a bit more info. – Sorin Jan 26 '12 at 00:24