Parameter expansion is a powerful feature in bash (and other POSIX-compliant shells) that allows you to manipulate variables and their values. It's commonly used for tasks like providing default values, removing prefixes or suffixes, and performing simple text transformations.
The basic syntax of parameter expansion is ${parameter}
or ${parameter:-word}
.
${parameter}
: Expands to the value of parameter
.${parameter:-word}
: If parameter
is unset or null, expands to word
; otherwise, expands to the value of parameter
.${variable:-defaultValue}
If variable
is not set or is null, this will return defaultValue
.${parameter:=word}
word
to parameter
if parameter
is unset or null; otherwise, retains the value of parameter
.${variable:?errorMessage}
If variable
is not set or is null, this will display errorMessage
.${variable:offset:length}
This will return a substring of variable
starting at offset
and of length length
.${#variable}
This will return the length of the value stored in variable
.${variable/pattern/replacement}
This will replace the first match of pattern
with replacement
in variable
.${variable//pattern/replacement}
This will replace all matches of pattern
with replacement
in variable
.${parameter:+word}
word
if parameter
is set and not null; otherwise, expands to null.${parameter#prefix}
prefix
from the beginning of parameter
.${parameter%suffix}
suffix
from the end of parameter
.${parameter:start:length}
length
from parameter
, starting at position start
. If length
is omitted, extracts to the end of the string.Let's illustrate these operators with examples:
# Example variables
unset var1
var2="value2"
var3=""
# Use default value
echo "${var1:-default}" # Output: default
echo "${var2:-default}" # Output: value2
# Assign default value
echo "${var1:=default}" # Output: default (and sets var1 to "default")
echo "${var2:=default}" # Output: value2 (var2 already has a value)
# Use alternate value
echo "${var1:+alt}" # Output: (var1 is unset or null, so no output)
echo "${var2:+alt}" # Output: alt
# Remove prefix
var="prefix_value"
echo "${var#prefix_}" # Output: value
# Remove suffix
var="value_suffix"
echo "${var%suffix}" # Output: value
# Substring
var="substring"
echo "${var:3:5}" # Output: string
Parameter expansion is commonly used in scripting for tasks such as:
Parameter expansion is a versatile feature in bash that allows for dynamic manipulation of variables and their values. By mastering parameter expansion, you can write more concise and flexible shell scripts for a variety of tasks.