Bash Variables: Case Sensitive or Not

Bash variables: case sensitive or not?

Yes, it is case sensitive, just like the rest of UNIX. $date and $DATE are two different variables. makefile and Makefile are two different files. -h and -H are two distinct flags (usually).

Correct Bash and shell script variable capitalization

By convention, environment variables (PAGER, EDITOR, ...) and internal shell variables (SHELL, BASH_VERSION, ...) are capitalized. All other variable names should be lower case.

Remember that variable names are case-sensitive; this convention avoids accidentally overriding environmental and internal variables.

Keeping to this convention, you can rest assured that you don't need to know every environment variable used by UNIX tools or shells in order to avoid overwriting them. If it's your variable, lowercase it. If you export it, uppercase it.

Make the if statement case insensitive in bash

With Bash 4 or newer, you can use a parameter expansion to lowercase the string:

if [[ ${check_headers,,} == "x-requested-id"* ]]; then

How can I make a bash script case insensitive?

In bash, you can use the ,, parameter expansion to lowercase a variable value:

#! /bin/bash

read -p Name: name
case ${name,,} in
(john) echo Hi John! ;;
(jane) echo Hallo Jane! ;;
(jack) echo Long time no see, Jack! ;;
(*) echo "I don't know you." ;;
esac

Case insensitive comparison in Bash

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

Linux: Environment Variable setting to ignore case sensitivity?

grep looks at the envirorment variable GREP_OPTIONS
so you can do

export GREP_OPTIONS="--ignore-case"
grep a <<< "A"

Case insensitive comparison of strings in shell script

if you have bash

str1="MATCH"
str2="match"
shopt -s nocasematch
case "$str1" in
$str2 ) echo "match";;
*) echo "no match";;
esac

otherwise, you should tell us what shell you are using.

alternative, using awk

str1="MATCH"
str2="match"
awk -vs1="$str1" -vs2="$str2" 'BEGIN {
if ( tolower(s1) == tolower(s2) ){
print "match"
}
}'


Related Topics



Leave a reply



Submit