How to convert a string from uppercase to lowercase in Bash?

raga picture raga · Jul 9, 2012 · Viewed 187.5k times · Source

I have been searching to find a way to convert a string value from upper case to lower case. All the search results show approaches of using tr command.

The problem with the tr command is that I am able to get the result only when I use the command with echo statement. For example:

y="HELLO"
echo $y| tr '[:upper:]' '[:lower:]'

The above works and results in 'hello', but I need to assign the result to a variable as below:

y="HELLO"
val=$y| tr '[:upper:]' '[:lower:]'
string=$val world

When assigning the value like above it gives me an empty result.

PS: My Bash version is 3.1.17

Answer

kev picture kev · Jul 9, 2012

If you are using bash 4 you can use the following approach:

x="HELLO"
echo $x  # HELLO

y=${x,,}
echo $y  # hello

z=${y^^}
echo $z  # HELLO

Use only one , or ^ to make the first letter lowercase or uppercase.