Function Files

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.

  1. Create a directory, where you want your own function files to live, say: ~/.zshfunctions
  2. 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.
  3. Copy the function file you want to that directory: cp /path/to/_foo ~/.zshfunctions
  4. To avoid problems due to ~/.zcompdump, remove that file: rm -f ~/.zcompdump
  5. Restart zsh: exec zsh
config/functions.txt · Last modified: 2015/10/24 22:53 by opk