Shell Scripting: Convert Uppercase to Lowercase

I‘ve a small shell script and I would like to convert all incoming user input to lowercase using a shell script. How do I convert uppercase words or strings to a lowercase or vise versa on Unix-like / Linux bash shell?

Use the tr command to convert all incoming text / words / variable data from upper to lower case or vise versa (translate all uppercase characters to lowercase). Bash version 4.x+ user [donotprint][/donotprint]can use parameter expansion to modify the case of alphabetic characters in parameter.

Convert all text in a file from UPPER to lowercase

To translate or delete characters use tr command. The basic syntax is:

tr 'set1' 'set2' input

OR

tr 'set1' 'set2' input > output

Type the following command at shell prompt:
$ tr '[:upper:]' '[:lower:]' output.txt
$ cat output.txt

Task: Convert Data Stored in a Shell Variable From UPPER to lowercase:

Type the following command:
$ echo $VAR_NAME | tr '[:upper:]' '[:lower:]'
$ echo $VAR_NAME | tr '[:lower:]' '[:upper:]'

Bash version 4.x+: Uppercase to lowercase or vice versa

The bash version 4.x+ got some interesting new features. Type the following commands to convert $y into uppercase:

y="this Is A test"
echo "${y^^}"

y="this Is A test"
echo "${y^^}"

Sample outputs:

THIS IS A TEST

Type the following commands to convert $y into lowercase:

y="THIS IS a TeSt"
echo "${y,,}"

y="THIS IS a TeSt"
echo "${y,,}"

Sample outputs:

this is a test

Sample Shell Script

#!/bin/bash
# get filename
echo -n "Enter File Name : "
read fileName
 
# make sure file exits for reading
if [ ! -f $fileName ]; then
  echo "Filename $fileName does not exists."
  exit 1
fi
 
# convert uppercase to lowercase using tr command
tr '[A-Z]' '[a-z]' < $fileName
 
# Note Bash version 4 user should use builtins as discussed above

#!/bin/bash
# get filename
echo -n "Enter File Name : "
read fileName # make sure file exits for reading
if [ ! -f $fileName ]; then
echo "Filename $fileName does not exists."
exit 1
fi # convert uppercase to lowercase using tr command
tr ‘[A-Z]’ ‘[a-z]’ < $fileName # Note Bash version 4 user should use builtins as discussed above

Recommended readings:

# Additional correction by D.K.; Editing by VG – log #

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.