Bash Script to Convert String to Lowercase
lowercase_string=${string,,}, which changes all uppercase letters in string to lowercase.Examples
How to Think About It
,, operator inside parameter expansion, which automatically transforms all uppercase letters in the string to lowercase.Algorithm
Code
#!/bin/bash input="Hello World!" lowercase_string=${input,,} echo "$lowercase_string"
Dry Run
Let's trace the input "Hello World!" through the code
Set input string
input="Hello World!"
Convert to lowercase
lowercase_string=${input,,} -> "hello world!"
Print result
echo prints "hello world!"
| input | lowercase_string |
|---|---|
| Hello World! | hello world! |
Why This Works
Step 1: Parameter Expansion
The ${variable,,} syntax is Bash's parameter expansion that converts all uppercase letters in variable to lowercase.
Step 2: No External Commands
This method uses built-in Bash features, so it is fast and does not require calling external programs like tr.
Step 3: Simple and Readable
The syntax is concise and easy to read, making scripts cleaner and easier to maintain.
Alternative Approaches
#!/bin/bash input="Hello World!" lowercase_string=$(echo "$input" | tr '[:upper:]' '[:lower:]') echo "$lowercase_string"
#!/bin/bash input="Hello World!" lowercase_string=$(echo "$input" | awk '{print tolower($0)}') echo "$lowercase_string"
Complexity: O(n) time, O(n) space
Time Complexity
The operation processes each character once to convert uppercase letters to lowercase, so it runs in linear time relative to string length.
Space Complexity
It requires space proportional to the input string length to store the converted string, so space complexity is linear.
Which Approach is Fastest?
Bash parameter expansion is fastest because it avoids spawning external processes, unlike tr or awk.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Bash parameter expansion (${string,,}) | O(n) | O(n) | Fastest, simplest for Bash scripts |
| tr command | O(n) | O(n) | Portable, works in older shells |
| awk command | O(n) | O(n) | Useful if awk is already used |
${string,,} for fast and simple lowercase conversion without external commands.