Peter Penzov
Peter Penzov

Reputation: 1678

Make input character case not sensitive

I want to use this script to to access capital letters and small letters.

### User prompts
read -p "Would you like us to perform the option: \"(Y|N)\" " inPut

case $inPut in
# echoing a command encapsulated by
# backticks (``) executes the command
"Y") echo 'Starting.....'
donwload_source_code
;;

# depending on the scenario, execute the other option
# or leave as default
"N") echo 'Stopping execution'
exit
;;

esac

For example Y and y to lead to one switch case. Is there any solution?

Upvotes: 2

Views: 180

Answers (3)

chepner
chepner

Reputation: 531075

You can set the nocasematch option to perform case-insensitive matches.

$ foo=Y
$ case $foo in y) echo "matched y" ;; *) echo "no match" ;; esac
no match
$ shopt -s nocasematch
$ case $foo in y) echo "matched y" ;; *) echo "no match" ;; esac
matched y

Upvotes: 0

Inian
Inian

Reputation: 85570

Just change the construct in case to y|Y to work with all versions of bash

### User prompts
read -p "Would you like us to perform the option: \"(Y|N)\" " inPut

case $inPut in
# echoing a command encapsulated by
# backticks (``) executes the command
y|Y) echo 'Starting.....'
donwload_source_code
;;

# depending on the scenario, execute the other option
# or leave as default
n|N) echo 'Stopping execution'
exit
;;

esac

Upvotes: 1

P....
P....

Reputation: 18371

Change one line in existing code: More info Here . Note that bash Version 4+ is needed for this. As an alternate : echo $var |awk '{print toupper($0)}' can be used.

case ${inPut^} in

Example:

sh-4.1$ var=y
sh-4.1$ echo $var
y                           #Lower case
sh-4.1$ echo ${var^}        #Modified to upper case
Y
sh-4.1$

Modified script:

### User prompts
read -p "Would you like us to perform the option: \"(Y|N)\" " inPut

case ${inPut^} in
# echoing a command encapsulated by
# backticks (``) executes the command
"Y") echo 'Starting.....'
donwload_source_code
;;

# depending on the scenario, execute the other option
# or leave as default
"N") echo 'Stopping execution'
exit
;;

esac

Upvotes: 3

Related Questions