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 intolower()
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
Related videos on Youtube
Author by
Niresh
Updated on September 18, 2022Comments
-
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.sh
isSTRING
orStRiNg
the result is going to be false.How can I ignore the case in the
if
condition?-
mpy over 10 yearsYou should use
[[ "$1" == "string" ]]
instead of[ $1 == "string" ]
. Otherwise you will get into trouble, if$1
contains spaces or is empty.
-
-
glenn jackman over 10 yearsbetter to quote
"$a"
-
gniourf_gniourf over 10 yearsThere's also the
nocasematch
shell option that could be used.