How to convert a string from uppercase to lowercase in Bash? [duplicate]

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

1

7 Answers

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.

9

One way to implement your code is

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

This uses $(...) notation to capture the output of the command in a variable. Note also the quotation marks around the string variable -- you need them there to indicate that $val and world are a single thing to be assigned to string.

If you have bash 4.0 or higher, a more efficient & elegant way to do it is to use bash builtin string manipulation:

y="HELLO" string="${y,,} world" 
2

Note that tr can only handle plain ASCII, making any tr-based solution fail when facing international characters.

Same goes for the bash 4 based ${x,,} solution.

The awk tool, on the other hand, properly supports even UTF-8 / multibyte input.

y="HELLO" val=$(echo "$y" | awk '{print tolower($0)}') string="$val world" 

Answer courtesy of liborw.

1

Why not execute in backticks ?

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

This assigns the result of the command in backticks to the variable x. (i.e. it's not particular to tr but is a common pattern/solution for shell scripting)

You can use $(..) instead of the backticks. See here for more info.

5

I'm on Ubuntu 14.04, with Bash version 4.3.11. However, I still don't have the fun built in string manipulation ${y,,}

This is what I used in my script to force capitalization:

CAPITALIZED=`echo "${y}" | tr '[a-z]' '[A-Z]'` 
4

If you define your variable using declare (old: typeset) then you can state the case of the value throughout the variable's use.

$ declare -u FOO=AbCxxx $ echo $FOO ABCXXX 

"-l" does lc.

1

This worked for me. Thank you Rody!

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

one small modification, if you are using underscore next to the variable You need to encapsulate the variable name in {}.

string="${val}_world" 

You Might Also Like