Ignore case from user input

5,509

Solution 1

Assuming you are using bash 4.0+:

${1,,}

Otherwise, tr or awk should work:

var=$(echo "$1" | awk '{print tolower($0)}')
var=$(echo "$1" | tr '[:upper:]' '[:lower:]')

Summaries:

  • Awk takes in the input and simply prints $0 (the whole input line) after using the built in tolower() function.

  • Tr looks pretty self explanatory, but let me know if you have questions on it.

Solution 2

declare has a lower-case function:

declare -l str=$1
[[ $str = "string" ]] && echo true || echo false
Share:
5,509

Related videos on Youtube

Niresh
Author by

Niresh

Updated on September 18, 2022

Comments

  • Niresh
    Niresh over 1 year

    I'm trying to write a script to catch user input. The script should ignore the case.

    Consider this script foo.sh:

    if [ $1 == "string" ]; then
      echo true
    else
      echo false
    fi
    

    If the input of foo.shis STRING or StRiNg the result is going to be false.

    How can I ignore the case in the if condition?

    • mpy
      mpy over 10 years
      You should use [[ "$1" == "string" ]] instead of [ $1 == "string" ]. Otherwise you will get into trouble, if $1 contains spaces or is empty.
  • glenn jackman
    glenn jackman over 10 years
    better to quote "$a"
  • gniourf_gniourf
    gniourf_gniourf over 10 years
    There's also the nocasematch shell option that could be used.