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 promp
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.
try this one too:
[[ $yn =~ "^[yY](es)?$" ]]
Here's an answer that uses extended patterns instead of regular expressions:
shopt -s nocasematch
shopt -s extglob
while [[ $yn = y?(es) ]]; do
...
done
Note that starting in version 4.1, bash
always uses extended patterns inside the [[ ... ]]
conditional expression, so the shopt
line is no necessary.
I prefer using grep -E
or egrep
for short:
while egrep -iq '^(y|yes)$' <<< $yn; do
your_logic_here
done
Here you have explanations from grep
manual:
-i, --ignore-case
Ignore case distinctions in both the PATTERN and the input files. (-i is specified by POSIX.)
-q, --quiet, --silent
Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. (-q is specified by POSIX.)
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 ]]