Bash How to Convert Text to Lowercase
In Bash, convert a string to lowercase using
${variable,,} syntax, for example: echo "${text,,}".Examples
InputHELLO
Outputhello
InputBash Script
Outputbash script
Input123 ABC xyz!
Output123 abc xyz!
How to Think About It
To convert text to lowercase in Bash, you take the original string and apply a built-in parameter expansion that changes all uppercase letters to lowercase. This is simple and does not require external commands, making it efficient and easy to use.
Algorithm
1
Get the input string.2
Use Bash parameter expansion with double commas to convert all uppercase letters to lowercase.3
Output the converted lowercase string.Code
bash
#!/bin/bash text="Hello World!" lowercase_text="${text,,}" echo "$lowercase_text"
Output
hello world!
Dry Run
Let's trace the example 'Hello World!' through the code
1
Set variable
text = 'Hello World!'
2
Convert to lowercase
lowercase_text = '${text,,}' results in 'hello world!'
3
Print result
Output: 'hello world!'
| Step | Variable | Value |
|---|---|---|
| 1 | text | Hello World! |
| 2 | lowercase_text | hello world! |
| 3 | echo output | hello world! |
Why This Works
Step 1: Parameter Expansion
The ${variable,,} syntax tells Bash to convert all uppercase letters in variable to lowercase.
Step 2: No External Commands
This method uses Bash's built-in features, so it is faster and simpler than calling external tools like tr.
Step 3: Works on Strings
It works on any string stored in a variable, preserving non-letter characters unchanged.
Alternative Approaches
Using tr command
bash
text="Hello World!" echo "$text" | tr '[:upper:]' '[:lower:]'
This uses an external command and is portable but slightly slower.
Using awk
bash
text="Hello World!" echo "$text" | awk '{print tolower($0)}'
Another external tool approach, useful if you already use awk in your script.
Complexity: O(n) time, O(n) space
Time Complexity
The operation processes each character once, so time grows linearly with string length.
Space Complexity
A new string is created for the lowercase result, so space also grows linearly with input size.
Which Approach is Fastest?
Using Bash parameter expansion is fastest since it avoids external commands, unlike tr or awk.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Bash parameter expansion | O(n) | O(n) | Fastest, simplest for Bash scripts |
| tr command | O(n) | O(n) | Portable, works in all shells |
| awk command | O(n) | O(n) | When awk is already used in script |
Use
${variable,,} for quick and efficient lowercase conversion in Bash scripts.Beginners often forget the double commas
,, and use single comma which does not convert to lowercase.