Parameter expansion in Bash allows you to manipulate and expand the values of variables. It provides a way to perform string manipulation, substitution, or extraction operations on variable values.
Here are some commonly used parameter expansion techniques in Bash:
- Variable substitution: You can substitute the value of a variable using the
${variable}
syntax. If the variable is unset or empty, you can provide a default value.Example:
name="John"
echo "Hello, ${name}!" # Output: Hello, John!
In this example, the value of the name
variable is substituted into the string using ${name}
.
- Default value substitution: If a variable is unset or empty, you can specify a default value to be used instead.Example:
age=""
echo "Age: ${age:-Unknown}" # Output: Age: Unknown
In this example, the value of the age
variable is empty. The ${age:-Unknown}
syntax substitutes the default value “Unknown” since age
is unset or empty.
3. Length of a string: You can determine the length of a string using ${#variable}
.Example:
message="Hello, world!"
echo "Length: ${#message}" # Output: Length: 13
In this example, ${#message}
returns the length of the string stored in the message
variable.
4. String manipulation: You can perform various string manipulation operations, such as substring extraction, pattern matching, and replacement, using different parameter expansion techniques. Example:
greeting="Hello, world!"
echo "Substring: ${greeting:7:5}" # Output: Substring: world
echo "Pattern match: ${greeting#Hello, }" # Output: Pattern match: world!
echo "Replacement: ${greeting/world/John}" # Output: Replacement: Hello, John!
In this example, different parameter expansion forms are used to extract a substring, perform a pattern match, and perform a replacement operation on the greeting
variable.
These are just a few examples of parameter expansion in Bash. Bash provides a rich set of expansion options and techniques to manipulate and extract information from variable values. You can refer to the Bash documentation for a comprehensive list of available expansions and their usage.