Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case insensitive comparison in Bash

Tags:

syntax

bash

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?

like image 900
user2150250 Avatar asked Mar 21 '13 21:03

user2150250


2 Answers

shopt -s nocasematch
while [[ $yn == y || $yn == "yes" ]] ; do

or :

shopt -s nocasematch
while [[ $yn =~ (y|yes) ]] ; do

Note

  • [[ 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
    Unless you're writing for POSIX sh, we recommend [[.
  • The =~ 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 ]]
like image 143
Gilles Quenot Avatar answered Sep 20 '22 04:09

Gilles Quenot


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.

like image 25
Riot Avatar answered Sep 20 '22 04:09

Riot