rnd's website logoshell parameter expansion

This is a small cheat sheet to remind me of how parameter expansion works in unix shells.

shell parameter expansion

  • ${a-b} # return $a if set, otherwise b

  • ${a:-b} # return $a if set and not null, otherwise b

  • ${a=b} # return $a if set, otherwise set $a to b

  • ${a:=b} # return $a if set and not null, otherwise set $a to b

  • ${a?b} # return $a if set, otherwise crash

  • ${a:?b} # return $a if set or null, otherwise crash

  • ${a+b} # return b if $a set, otherwise null

  • ${a:+b} # return b if $a set or null, otherwise null

  • ${#a} # return length of $a

  • ${a:b:c} # return c characters starting from offset b in $a

  • ${a%b} # remove smallest pattern b at the end of $a

  • ${a%%b} # remove largest pattern b at the end of $a

  • ${a#b} # remove smallest pattern b at the start of $a

  • ${a##b} # remove largest pattern b at the start of $a

non-standard (ok in busybox ash and bash, not ok in dash)

  • ${a/b/c} # replace b with c in $a
Follow me on Mastodon This page made with Vim Best viewed in Firefox