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.
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
...
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 if
varis "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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With