10 Forms of Bash Shell Parameter Expansion
If I look at my search history with the word “bash” in it, the most frequently searched phrases turn out to be like “trim suffix bash” and “set bash variable if empty”.
It seems I write Bash scripts frequently enough to need these, but not frequently enough to remember these simple Bash shell parameter expansion forms.
In this blog post I am going to keep a list of 10 forms of Bash shell parameter expansion, that I hope will save me a visit to google.com.
In Bash, the basic form of parameter expansion is ${var}
. But there’s more. The official documentation has a detailed list and description of how else you can expand a parameter: https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html
${var:-fallback}
: Use fallback
, If var
Is Unset
|
|
${var:+substitute}
: Use substitute
, If var
Is Set
|
|
${#var}
: Length of var
|
|
${var:start}
: Substring of var
Starting from start
|
|
${var:start:length}
: Substring of var
of Size length
Starting from start
|
|
${var#prefix}
: Trim prefix
From var
|
|
${var%suffix}
: Trim suffix
From var
|
|
${var/pattern/substitute}
: Replace pattern
in var
with substitute
|
|
${var^}
: Change Letter Case in var
|
|
${var@Q}
: Quoted String
|
|
This post is 66th of my #100DaysToOffload challenge. Want to get involved? Find out more at 100daystooffload.com.
comments powered by Disqus