Domanda

I have a script that assign a list of names to a variable

$a = tom jerry albert yoyo etc 

I need to check if the content of another variable within my script matches one of the names assigned to this variable. How can I do this? My other variable name is $name. So my logic should be.

if  $name contains in $a
   echo  it matches
esle
    echo it does not match 
fi

So is my $name is equal to tom then I like to echo "it matches"

Can you please advice?

Thanks

È stato utile?

Soluzione

Ideally you would want to use an array to store the names and iterate over it to test for a match:

#!/bin/bash

contains()
{
    local element
    for element in "${@:2}"; do
        [ "${element}" = "$1" ] && return 0
    done
    return 1
}

a=(tom jerry albert yoyo)

for name in tom to foo; do
    if contains "${name}" "${a[@]}"; then
        echo "${name} matches"
    else
        echo "${name} doesn't match"
    fi
done

$ ./t.sh
tom matches
to doesn't match
foo doesn't match

You could even pass by "reference" by using variable indirection, that way you only have to pass the name of the array to contains which you want to match against:

contains()
{
    local element
    for element in "${!1}"; do
        [ "${element}" = "$2" ] && return 0
    done
    return 1
}

names=(tom jerry albert yoyo)

for name in tom to foo; do
    if contains "names" "${name}"; then
        echo "${name} matches"
    else
        echo "${name} doesn't match"
    fi
done

Altri suggerimenti

You could loop over the $list variable and check for matches, as in the following excerpt:

list="tom jerry albert yoyo etc"

name=tom

for item in $list
do
        if [[ "$item" == "$name" ]]
        then
                echo it matches
        else
                echo it does not match 
        fi
done

For a completely portable solution, you could use case. Something like

case " $list " in
    *" $name "* ) echo "'$name' included in '$list'" ;;
    * ) echo not. ;;
esac

Ok I found the answer

if [[ "$a" =~ "$name" ]] && [ -n "$name" ]; then
   echo it matches
else
echo it does not match
fi

Cheers

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top