Search code examples
arraysbashstring-comparison

Bash, compare string to arrayvalue


i try to match a parameter with some array content. At the if clauses should be true, but it wont be. At the output before compare i got this:

VAL: drei_01 AND: drei

#!/bin/bash

array=( null_01 eins_01 zwei_01 drei_01 vier_01 )

lookarr() {
    maxc=${#array[@]}
    mbool=0

    for((i=0; i<$maxc; i++))
    do
        val=${array[$i]}
        echo "VAL:  $val AND: $1"

        if [[ $1 == *" $val "* ]]; then
            echo "TESTENTRY1"
            #do something
            mbool=1
            break
        fi
    done

    if [[ $mbool -eq 0 ]]; then
        echo "TESTENTRY2"
        #do something else
    fi

}

lookarr drei

thanks


Solution

  • Your if statement isn't matching because it is back-to-front and has extra spaces. For drei to match drei_01 you can replace your if statement with:

    if [[ "$val" == *"$1"* ]]; then