In zsh, a function can be kept in a file, like this:
echo "Hello World."
Say, that's a file called
hello somewhere in your $fpath. In that case you can
autoload hello and use a function called hello, which will indeed print out "Hello World.". And that's the whole trick.
One option of autoload, you might want to know about is
-U. That option suppresses aliases from being expanded while the function is loading. You may also want to use
-z to force zsh-style autoloading - which is the default but read the part about KSH_AUTOLOAD in zshoptions(1) to understand the difference.
Adding and overwriting function files
Let's say you've written a completion function named _foo and you want it to be available whenever you use the shell.
- Create a directory, where you want your own function files to live, say:
- Add this directory at the beginning of your $fpath:
fpath=( ~/.zshfunctions $fpath )
- The "at the beginning" part is important, if you want your file to take precedence over files from the system wide paths.
- Copy the function file you want to that directory:
cp /path/to/_foo ~/.zshfunctions
- To avoid problems due to ~/.zcompdump, remove that file:
rm -f ~/.zcompdump
- Restart zsh: