POSIX Shell Parameter Expansion
Parameter Expansion
Reference | Set and Not Null | Set but Null | Unset |
---|---|---|---|
${parameter-word} |
substitute parameter | substitute null | substitute word |
${parameter:-word} |
substitute parameter | substitute word | substitute word |
${parameter+word} |
substitute word | substitute word | substitute null |
${parameter:+word} |
substitute word | substitute null | substitute null |
${parameter=word} |
substitute parameter | substitute null | assign word |
${parameter:=word} |
substitute parameter | assign word | assign word |
${parameter?word} |
substitute parameter | error, exit | error, exit |
${parameter:?word} |
substitute parameter | substitute null | error, exit |
Substring
${parameter#pattern}
${parameter##pattern}
Expand to parameter with the matching pattern from the beginning deleted. The one with a
single `#' matches the shortest pattern (lazy), while the one with `##' matches the longest pattern (greedy).
For example, variable `my_shell_path' is set to `/usr/local/bin/sh
',
`${my_shell_path#*/}
' is `usr/local/bin/sh
' (`*/
' matches `/`), while
`${my_shell_path##*/}
' is `sh
' (`*/
' matches `/usr/local/bin/').
${parameter%pattern}
${parameter%%pattern}
Expand to parameter with the matching pattern from the end deleted. Similar to `#' vs `##', a single `%' matches shortest pattern, while `%%' matches longest pattern.
Parameter Substring by Offsets
There is no built-in expansion to extract a substring from a parameter by offsets
(`${parameter:start:end}
' is a GNU BASH extension), but it can be achieved with help of `cut'
utility: `parameter=`printf "%s" "$parameter" | cut -cM-N`
', where `M' and `N' is the start and end
offset (inclusive, counted from 1) respectively. For example, for a parameter whose value is `abcdefg',
`parameter=`printf "%s" "$parameter" | cut -c1-3`
' will make parameter's value `abc'.
Parameter Substitution
There is no built-in expansion for parameter substitution for POSIX Shell, either, and likewise, it can be achieved by multiple utilities, such as `tr' or `sed'. Take `sed' as an example, `parameter=`printf "%s" "$parameter" | sed -e 's/cat/dog/g'`
' will substitute all occurrences of `cat' in the parameter to `dog'.