Case insensitive comparison in Bash

前端 未结 5 1699
时光说笑
时光说笑 2021-01-05 10:37

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

5条回答
  •  时光说笑
    2021-01-05 11:15

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

提交回复
热议问题