Convert between Uppercase and Lowercase in Bash

In this article, we will show you how to convert a string to uppercase or lowercase in Bash.

1. Convert to Uppercase or Lowercase

  • If you append the keyword ^^ to the right of a string, it will be converted to uppercase.
  • If you append the keyword ,, to the right of a string, it will be converted to lowercase.

This is an example of how to convert a string to uppercase or lowercase.

#!/bin/bash

str="ApPlE"

uppercase=${str^^}

lowercase=${str,,}

echo "Uppercase: ${uppercase}"

echo "Lowercase: ${lowercase}"

Output:

$ bash example.sh
Uppercase: APPLE
Lowercase: apple

2. Converting only certain characters to uppercase and lowercase

For example, if you input any character after the keyword ^^ like ^^a, the character will be converted to uppercase in the string. The same applies to ,,A, where A is converted to lowercase in the string.

#!/bin/bash

str="apple"
echo ${str^^p}

str2="APPLE"
echo ${str2,,E}

Output:

$ bash example.sh
aPPle
APPLe

3. Combining with other strings

This is an example of combining a string converted to uppercase and lowercase with another string.

#!/bin/bash

str="ApPlE"
str2="Juice"

echo "${str^^} ${str2}"

echo "${str,,} ${str2}"

Output:

$ bash example.sh
APPLE Juice
apple Juice
codechachaCopyright ©2019 codechacha