ZSH filepath modifiers
15 Jan 2023zsh 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 likewhich):qfor quoting,:Ufor unquoting,:xfor quoting individual words:lfor lowercase,:ufor uppercase:2:10takes a substring from2to10- Those modifiers can be applied directly to glob patterns (
src/**/*.zsh(:t:r))
Want to add something ? Feel free to get in touch on Bluesky : @pixelastic.bsky.social