Sorry if a question like this already has an answer, I wasn't really sure how to word this, so I'll try my best.
How can I make an if statement match an entire string, OR an entire string with an extra character?
Let's say the $animals
variable has ,dog,cat,pig,bird,goat,
stored in it. I want to see if the user-defined variable $your_pet
is either one of the comma-separated values OR if it is with an "s" at the end.
So maybe something that would work like:
your_pet=bird
if [[ "${your_pet}" == ,*"${animals}"*, || "${your_pet}"s == ,*"${animals}"*, ]]
then
....
However , I need to check if $your_pet
ends in an "s" or not, and accept it if it does or doesn't. (The above code is untested but I am almost certain it would not work).
Here are all of the allowed values of $your_pet
:
dog
dogs
cat
cats
pig
pigs
bird
birds
goat
goats
And here are some examples of what would not be allowed:
my dog
my dogs
dog
hamster
hamsters
I feel like using regex in the if statement would do the trick but I don't know that much about regex to know what to use. (if regex is even needed in a situation like this)
Using bash 3.2.57(1)-release on OS X 10.11.6 El Capitan
Thanks
You can remove the s
(if present) and then compare if it matches
your_pet=bird
if [[ "$animals" =~ ",${your_pet%s}," ]]
then
...
however, take into account other plurals like goose, geese .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.