ZSH filepath modifiers

zsh comes bundled with variable modifier to alter filepaths and extract the relevant parts.

Given the following code, we can display $filepath in a lot of different ways:

mkdir -p /tmp/subdir
cd /tmp
local filepath=./subdir/file.zsh

| Name | Output | Modifier | Mnemonic | | --------- | ---------------------- | ----------------- | ------------------ | | Absolute | /tmp/subdir/file.zsh | ${filepath:a} | absolute | | Basename | file.zsh | ${filepath:t} | tail | | Filename | file | ${filepath:t:r} | tail rest | | Extension | zsh | ${filepath:e} | extension | | Dirpath | /tmp/subdir | ${filepath:a:h} | absolute h ead |

For clarity

  • tail is everything after the last /
  • head is everything before the last /
  • extension is everything after the last .
  • rest is everything before the last .

Other goodies

  • ${~filepath} will expand ~ to their full path, while ${filepath/#$HOME/~} will use ~ instead of home path
  • :command gives you the executable path of a command (a bit like which)
  • :q for quoting, :U for unquoting, :x for quoting individual words
  • :l for lowercase, :u for uppercase
  • :2:10 takes a substring from 2 to 10
  • Those modifiers can be applied directly to glob patterns (src/**/*.zsh(:t:r))

Tags : #zsh

Want to add something ? Feel free to get in touch on Twitter : @pixelastic