12

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.

hhh0505
  • 357
  • 1
  • 2
  • 11

3 Answers3

3

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
   ...
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
  • tried that , same thing. To give more context im using aws API to list IAM groups. var1=aws iam list-groups --output text | awk '{print $5}' | sed '$!s/$/,/ when i echo it from my script it shows up like this: admin, dev, stage – hhh0505 May 31 '18 at 19:24
  • This worked, my mistake with a typo. – hhh0505 May 31 '18 at 19:34
1

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.

Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151
  • Check my edit , i'm still unable to match the string out of the list. But your explanation that the others will match different scenarios is correct as that's what it was doing. – hhh0505 Jun 01 '18 at 16:24
0

Something like this?

#!/bin/bash
echo "please enter one,two or three"
read var

var1=["one","two","three"]


if [[ ${var} = *${var1}* ]]; then
    echo "${var} is in the list"
else
    echo "${var} is not in the list"
fi
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118