Bash中不区分大小写的比较
问题描述:
我正在尝试在不区分大小写的while语句中编写比较.基本上,我只是想简化以下内容,以便对用户显示是或否的问题提示...
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
或:
shopt -s nocasematch
while [[ $yn =~ (y|yes) ]] ; do
注意
-
[[
是bash关键字,与[
命令类似(但功能更强大).参见 http://mywiki.wooledge.org/BashFAQ/031 和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 ]]
-