Bash parameter expansion is a powerful feature that allows you to manipulate and transform variable values in shell scripts. It provides a concise way to modify strings, set default values, and perform various operations on variables without external commands.
The general syntax for parameter expansion is:
${parameter}
Where "parameter" can be a variable name, a special shell parameter, or an expression.
Set a default value if a variable is unset or null:
${variable:-default_value}
Example:
echo ${name:-"Guest"}
# Output: Guest (if name is unset)
Perform operations like substring extraction or replacement:
${string:position:length} # Substring extraction
${string/pattern/replacement} # Pattern replacement
Example:
text="Hello, World!"
echo ${text:7:5} # Output: World
echo ${text/World/Bash} # Output: Hello, Bash!
Get the length of a variable's value:
${#variable}
Example:
name="John Doe"
echo ${#name} # Output: 8
Remove matching patterns from the beginning or end of a string:
${variable#pattern} # Remove shortest matching prefix
${variable##pattern} # Remove longest matching prefix
${variable%pattern} # Remove shortest matching suffix
${variable%%pattern} # Remove longest matching suffix
Example:
file="script.tar.gz"
echo ${file#*.} # Output: tar.gz
echo ${file##*.} # Output: gz
echo ${file%.*} # Output: script.tar
echo ${file%%.*} # Output: script
Change the case of variable values:
${variable^} # Capitalize first character
${variable^^} # Convert to uppercase
${variable,} # Lowercase first character
${variable,,} # Convert to lowercase
Example:
text="hello WORLD"
echo ${text^} # Output: Hello WORLD
echo ${text^^} # Output: HELLO WORLD
echo ${text,} # Output: hello WORLD
echo ${text,,} # Output: hello world
{}
to avoid ambiguity, especially when concatenating with other text.Bash parameter expansion is a versatile feature that enhances your ability to work with variables efficiently. By mastering these techniques, you can write more concise and powerful shell scripts. Remember to consult the Bash manual for a complete list of parameter expansion options and their specific behaviors.
For more advanced scripting techniques, explore Bash command substitution and Bash process substitution.