How to convert a string to lower case in Bash ?

To convert a string to lowercase in Bash, you can use parameter expansion (Bash 4.0+) or the tr command. Here are both methods:

1. Using Parameter Expansion (Bash 4.0+)

str="HELLO World"
lower_str="${str,,}"  # Convert entire string to lowercase
echo "$lower_str"     # Output: "hello world"

Convert Specific Variables:

# For a variable:
filename="FILE.TXT"
lower_filename="${filename,,}"
echo "$lower_filename"  # Output: "file.txt"

Convert Directly in a Script:

input="INPUT_STRING"
echo "${input,,}"  # Output: "input_string"

2. Using tr (Portable for Older Bash Versions)

str="HELLO World"
lower_str=$(echo "$str" | tr '[:upper:]' '[:lower:]')
echo "$lower_str"  # Output: "hello world"

Explanation:

  • tr '[:upper:]' '[:lower:]': Translates all uppercase letters to lowercase.
  • Works on all systems, even with older Bash versions.

Key Notes:

  • Bash Version: Check your Bash version with bash --version. Parameter expansion (${var,,}) requires Bash 4.0+.
  • Portability: Use tr if compatibility with older systems is needed.
  • Special Characters: Both methods handle spaces and special characters if variables are quoted ("$str").

Example Workflow

#!/bin/bash

# Method 1 (Bash 4.0+)
str="Convert THIS Text"
echo "Parameter expansion: ${str,,}"

# Method 2 (tr)
echo "Using tr: $(echo "$str" | tr '[:upper:]' '[:lower:]')"

Output:

Parameter expansion: convert this text
Using tr: convert this text

Choose the method that aligns with your system’s capabilities!

Leave a Reply

Your email address will not be published. Required fields are marked *