I'm trying to write a comparison in a while statement that's case insensitive. Basically, I'm simply trying to shorten the following to act on a yes or no question prompt to the user ...
while[ $yn == "y" | $yn == "Y" | $yn == "Yes" | $yn == "yes" ] ; do
What would be the best way to go about this?
shopt -s nocasematch
while [[ $yn == y || $yn == "yes" ]] ; do
or :
shopt -s nocasematch
while [[ $yn =~ (y|yes) ]] ; do
[[
is a bash keyword similar to (but more powerful than) the [
command. See http://mywiki.wooledge.org/BashFAQ/031 and http://mywiki.wooledge.org/BashGuide/TestsAndConditionals[[
.=~
operator of [[
evaluates the left hand string against the right hand extended regular expression (ERE). After a successful match, BASH_REMATCH
can be used to expand matched groups from the pattern. Quoted parts of the regex become literal. To be safe & compatible, put the regex in a parameter and do [[ $string =~ $regex ]]
No need to use shopt or regex. The easiest and quickest way to do this (as long as you have Bash 4):
if [ "${var1,,}" = "${var2,,}" ]; then
echo "matched"
fi
All you're doing there is converting both strings to lowercase and comparing the results.
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