Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a string in a varaible with if statement [duplicate]

I am currently trying to find a string within a variable that outputs something like this:

one,two,three

My code:

echo "please enter one,two or three)
read var

var1=one,two,threee

if [[ "$var" == $var1 ]]; then
    echo "$var is in the list"
else
    echo "$var is not in the list"
fi

EDIT2:

I tried this but still not matching. Yo uwere correct about it not matching the exact string from previous answers as it was matching partial.

 groups="$(aws iam list-groups --output text | awk '{print tolower($5)}' | sed '$!s/$/,/' | tr -d '\n')"
echo "please enter data"
read "var"

if [ ",${var}," = *",${groups},"* ]; then
    echo "$var is in the list"
else
    echo "$var is not in the list"
fi

Trying this its still not matching the exact string as i need it to.

like image 661
hhh0505 Avatar asked May 31 '18 18:05

hhh0505


2 Answers

There might be other problems (like matching partial words), but if you use =~ (match) instead of == it would work for simple cases

if [[ "$var1" =~ "$var" ]]; then
   ...
like image 99
Diego Torres Milano Avatar answered Nov 19 '22 16:11

Diego Torres Milano


The other answers have a problem in that they'll treat matches of part of an item in the list as a match, e.g. if var1=admin,\ndev, \nstage(which I think is what you actually have), then it'll match ifvaris "e" or "min", or a bunch of other things. I'd recommend either removing the newlines from the variable (maybe by adding| tr -d '\n'` to the end of the pipeline that creates it), and using:

if [[ ",${var}," = *",${var1},"* ]]; then

(The commas around $var anchor it to the beginning and end of an item, and the ones around $var1 allow it to word for the first and last items.) You could also make it work with the newlines left in $var1, but that's the sort of thing that'll mess you up sooner or later anyway.

like image 1
Gordon Davisson Avatar answered Nov 19 '22 17:11

Gordon Davisson