使输入字符大小写不敏感

时间:2016-12-06 09:00:04

标签: 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") echo 'Starting.....'
donwload_source_code
;;

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

esac

例如Y和y导致一个开关盒。有没有解决方案?

3 个答案:

答案 0 :(得分:3)

更改现有代码中的一行:更多信息Here。请注意,此版本需要bash版本4+。作为替代方案:echo $var |awk '{print toupper($0)}'可以使用。

case ${inPut^} in

示例:

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$

修改过的脚本:

### 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

答案 1 :(得分:1)

只需将case中的构造更改为y|Y即可使用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

答案 2 :(得分:0)

您可以设置nocasematch选项以执行不区分大小写的匹配。

$ 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