Parameter Expansion

Parameter Expansion

In Bash, parameter expansion is a mechanism for manipulating and handling the contents of variables. Through parameter expansion, you can get the value of a variable, modify the value of a variable, or provide a default value for an unset variable.

Variable Expansion

The most common way.

var="Bash"
echo "Hello, ${var}!"

Default Value Expansion

Mark +

${var+DEFAULT}
  • var is undefined: returns an empty string.
  • var is defined:
    • is empty: returns DEFAULT.
    • is not empty: returns DEFAULT.
unset var
echo ${var+foo}
 

var=
echo ${var+foo}
foo

This mark can be used to determine whether a variable is undefined.

#!/usr/bin/env bash

if [ -n "${var+defined}" ]; then
    echo "var already defined"
else
    echo "var not defined"
fi

Note

If ${var+defined} is not used with double quotes, when an empty string is returned, the condition will become [ -n ], which is a valid condition, will not produce any errors, and its return value is true. Obviously this is unreasonable, so double quotes must be added.

Mark -

${var-DEFAULT}
  • var is undefined: returns DEFAULT.
  • var is defined:
    • is empty: returns var.
    • is not empty: returns var.
unset var
echo ${var-foo}
foo

var=
echo ${var-foo}
 

var and DEFAULT values may be the same, so they cannot be used to determine whether var is defined.

Mark :+

${var:+DEFAULT}
  • var is undefined: returns an empty string.
  • var is defined:
    • is empty: returns an empty string.
    • is not empty: returns DEFAULT.
var=abc
echo ${var:+foo}
foo

Mark :-

${var:-DEFAULT}
  • var is undefined: returns DEFAULT.
  • var is defined
    • is empty: returns DEFAULT.
    • is not empty: returns var.
unset var
echo ${var:-foo}
var=
echo ${var:-foo}

Both of the above two examples will output foo.

Mark :=

  • var is undefined: var=foo, returns var.
  • var is defined
    • is empty: var=foo, returns var.
    • is not empty: returns var.
unset var
echo ${var:=foo}
echo $var
foo
foo

String Operations

Extract Substring

var="heybro!"
echo ${var:3:4}
bro!

String Length

var="heybro!"
echo ${#var}
7

Remove Prefix

Remove the shortest match: use #, pattern */.

var="a/b/c"
echo ${var#*/}
b/c

Remove the longest match: use ##, pattern */.

var="a/b/c"
echo ${var##*/}
c

Remove Suffix

Remove the shortest match: use %, pattern /*.

var="a/b/c"
echo ${var%/*}
a/b

Remove the longest match: use %%, pattern /*.

var="a/b/c"
echo ${var%%/*}
a

Replace First Substring

var="aa bb aa"
echo ${var/aa/cc}
cc bb aa

Replace All Substrings

var="aa bb aa"
echo ${var//aa/cc}
cc bb cc