How to convert a string from uppercase to lowercase in Bash? [duplicate]
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
.
The correct 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"
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.