Case insensitive comparison in Bash

前端 未结 5 1705
时光说笑
时光说笑 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 10:59

    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.

    0 讨论(0)
  • 2021-01-05 11:03

    try this one too:

     [[ $yn =~ "^[yY](es)?$" ]] 
    
    0 讨论(0)
  • 2021-01-05 11:09

    Here's an answer that uses extended patterns instead of regular expressions:

    shopt -s nocasematch
    shopt -s extglob
    while [[ $yn = y?(es) ]]; do
      ...
    done
    

    Note that starting in version 4.1, bash always uses extended patterns inside the [[ ... ]] conditional expression, so the shopt line is no necessary.

    0 讨论(0)
  • 2021-01-05 11:13

    I prefer using grep -E or egrep for short:

    while egrep -iq '^(y|yes)$' <<< $yn; do
      your_logic_here
    done
    

    Here you have explanations from grep manual:

    -i, --ignore-case

    Ignore case distinctions in both the PATTERN and the input files. (-i is specified by POSIX.)

    -q, --quiet, --silent

    Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. (-q is specified by POSIX.)

    0 讨论(0)
  • 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 ]]
    0 讨论(0)
提交回复
热议问题