IN-Decent

Re-decentralizing internet with free software

Convert String to Upper or Lower Case in Bash

Posted at — Dec 26, 2021

Bash version 4+(initially released in Feb,2009) can convert case of a character to upper or lower case using parameter substitution feature. This feature also properly converts non english unicode characters where tr [:upper:] [:lower:] may not support it.

Below are the supported options with this feature,

  1. ${parameter^} - converts first character in string to upper case
  2. ${parameter^^} - converts all characters in string to upper case
  3. ${parameter,} - converts first character in string to lower case
  4. ${parameter,,} - converts all characters in string to lower case
  5. ${parameter~} - toggle case of first character in string (undocumented)
  6. ${parameter~~} - toggle case of all characters in string (undocumented)

Please find below example for using this feature.

string='HellO WoRlD'
echo ${string}   #HellO WoRlD
echo ${string^^} #HELLO WORLD
echo ${string,}  #hellO WoRlD
echo ${string,,} #hello world
echo ${string~}  #hellO WoRlD
echo ${string~~} #hELLo wOrLd
echo ${string}   #HellO WoRlD - string variable itself is unmodified

Note:

Some initial versions of Bash had a bug properly converting non english characters and Bash versions 4.3+ should work without any issues.

References:

  1. https://tldp.org/LDP/abs/html/bashver4.html
  2. https://tldp.org/LDP/abs/html/parameter-substitution.html#PARAMSUBREF
  3. https://stackoverflow.com/questions/2264428/how-to-convert-a-string-to-lower-case-in-bash#2265268