Parameter Expansion in Shell

Level 4164 keystrokes

Parameter expansion with # and % patterns splits a path into its parts without external commands: the file name, the directory, the extension and the name without the last extension.

Shell code

# A path with a double extension
1file="/path/to/document.tar.gz"
# Print the original value
2echo "Full: $file"
# ## removes the longest prefix matching */ (up to the last /) -> document.tar.gz
3echo "Basename: ${file##*/}"
# % removes the shortest suffix matching /* (from the last /) -> /path/to
4echo "Directory: ${file%/*}"
# ## with *. removes everything up to the last dot -> gz
5echo "Extension: ${file##*.}"
# % with .* removes only the last extension -> /path/to/document.tar
6echo "No ext: ${file%.*}"

Output

Full: /path/to/document.tar.gz
Basename: document.tar.gz
Directory: /path/to
Extension: gz
No ext: /path/to/document.tar
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.

  • "× 12
  • :× 5
  • /× 5
  • $× 5
  • .× 4
  • {× 4
  • }× 4
  • *× 4
  • #× 4
  • %× 2

More Shell examples at level 4

← Shell typing practice