Parameter Expansion in Shell

Level 4170 keystrokes

Parameter expansion edits a variable's value without external commands: ${var%pattern} removes a suffix, ${var##pattern} removes a prefix, and ${var:-default} supplies a fallback value.

Shell code

# A name with two dots
1filename="document.backup.txt"
# % removes the shortest suffix matching .* -> document.backup
2echo "Base: ${filename%.*}"
# ## removes the longest prefix matching *. -> txt
3echo "Extension: ${filename##*.}"
# :- uses the default because undefined is unset
4echo "Default: ${undefined:-default_value}"
# Strip the .txt suffix and append .pdf -> document.backup.pdf
5echo "Path: ${filename%.txt}.pdf"

Output

Base: document.backup
Extension: txt
Default: default_value
Path: document.backup.pdf
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Shell code and how often they appear.

  • "× 10
  • .× 6
  • :× 5
  • {× 4
  • }× 4
  • $× 4
  • *× 2
  • #× 2
  • %× 2
  • _× 1

More Shell examples at level 4

← Shell typing practice