Bash How to Convert Text to Uppercase
In bash, convert a string to uppercase using
${variable^^} or the tr '[:lower:]' '[:upper:]' command.Examples
Inputhello
OutputHELLO
InputBash Scripting
OutputBASH SCRIPTING
Input123abc!@
Output123ABC!@
How to Think About It
To convert text to uppercase in bash, you can use built-in parameter expansion which changes all lowercase letters to uppercase. Alternatively, you can pipe the text through the
tr command to translate lowercase characters to uppercase. Both methods handle letters only and leave other characters unchanged.Algorithm
1
Get the input string.2
Use bash parameter expansion <code>${variable^^}</code> to convert all lowercase letters to uppercase.3
Or pipe the string to <code>tr '[:lower:]' '[:upper:]'</code> to translate lowercase letters to uppercase.4
Print or return the converted uppercase string.Code
bash
#!/bin/bash input="Hello World!" # Using parameter expansion uppercase1=${input^^} echo "$uppercase1" # Using tr command echo "$input" | tr '[:lower:]' '[:upper:]'
Output
HELLO WORLD!
HELLO WORLD!
Dry Run
Let's trace the input 'Hello World!' through the uppercase conversion code
1
Set input variable
input = 'Hello World!'
2
Convert using parameter expansion
uppercase1 = ${input^^} = 'HELLO WORLD!'
3
Convert using tr command
echo 'Hello World!' | tr '[:lower:]' '[:upper:]' = 'HELLO WORLD!'
| Step | Input | Output |
|---|---|---|
| 1 | Hello World! | Hello World! |
| 2 | Hello World! | HELLO WORLD! |
| 3 | Hello World! | HELLO WORLD! |
Why This Works
Step 1: Parameter Expansion
The ${variable^^} syntax tells bash to convert all lowercase letters in variable to uppercase.
Step 2: tr Command
The tr command translates characters from one set to another; here it changes all lowercase letters to uppercase.
Alternative Approaches
awk command
bash
echo "hello world" | awk '{print toupper($0)}'
Uses awk's toupper function; useful if awk is preferred but slower than bash built-in.
sed command
bash
echo "hello world" | sed 's/.*/\U&/'
Uses sed to convert to uppercase; less common and may not work in all sed versions.
Complexity: O(n) time, O(n) space
Time Complexity
The conversion processes each character once, so time grows linearly with input length.
Space Complexity
A new string is created for the uppercase result, so space also grows linearly with input size.
Which Approach is Fastest?
Parameter expansion is fastest as it is built into bash; external commands like tr or awk add overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Parameter Expansion | O(n) | O(n) | Fastest, simplest in bash 4+ |
| tr Command | O(n) | O(n) | Works in older shells, external command |
| awk Command | O(n) | O(n) | When awk is preferred, slower |
| sed Command | O(n) | O(n) | Less common, compatibility varies |
Use
${variable^^} for quick uppercase conversion inside bash scripts without external commands.Forgetting that
${variable^^} requires bash version 4 or higher and won't work in older shells.