2.3 Parameter Expansions
In some scenarios you might find out that you want to slightly adjust how a variable is resolved from its classifier. In Bash, we have the ability to do this in-place without modification or extra variable assignments using something called a Parameter Expansion.
To use a parameter expansion, these are typically declared by calling the variable in the format of ${variable[expansion]}
Parameter expansions can be used to perform a number of different operations. This is most commonly to either lowercase or uppercase the entirety of a variable, though it can also be used for other things such as the ability to extract a substring from a variable, or to perform null coalescence.
Uppercase and Lowercase
To force a variable to all uppercase or lowercase, you should use the ^^
and ,,
expansions respectively.
# Lets set a variable with varying letter casing
example=AbCdEf
# Uppercase everything
echo ${example^^}
## Lowercase everything
echo ${example,,}
This can alternatively be achieved using @U
or @L
as well, and you also have the ability to capitalize only the first letter of a variable using @u
:
# Lets set a variable with varying letter casing
example=AbCdEf
# Uppercase everything
echo ${example@U}
# Lowercase everything
echo ${example@L}
# Define variables containing only lowercase or uppercase letters
lowercase=foo
# Change the case of only the first letter
echo ${lowercase@u}
Substring
Sometimes we might want to extract a small portion of argument rather than the whole argument. Bash provides us with a way to do this by providing a substring expansion :offset:length
example="Hello World"
# Prints ello Wo
echo ${example:1:7}
# Prints Hello
echo ${example::5}
Null Coalescence
Depending on circumstances, sometimes we may have a default value we would like to use in the event a variable is null or unset. Such cases are covered using an optional expansion :-value
test="Hello world!"
# Should set value to content of "test"
echo ${test:-This optional value should not be set}
# Should set value to optional fallback
echo ${missing:-This is a default value}
Bash also provides :+value
as an inverse expansion. This will instead substitute in another value should the variable contain a non-null value. Though, this on its own is not particularly useful.
Length
It is also possible to use parameter expansions to retrieve the length of a variable, you can do this using the length expansion ${#variable}
:
value="Test"
# Returns a length of 4
echo ${#value}
Substitution
Bash also supports simple find & replace all syntax in the form of a parameter expansion. To use this, use the substitution expansion //[find]/[replace]
:
value="Hello world!"
# Returns "Hello Bash!"
echo ${value//world/Bash}