autoload
tells zsh to look for a file in $FPATH
/$fpath
containing a function definition, instead of a file in $PATH
/$path
containing an executable script or binary.
Script
A script is just a sequence of commands that get executed when the script is run. For example, suppose you have a file called hello
like this:
echo "Setting 'greeting'"
greeting='Hello'
If the file is executable and located in one of the directories in your $PATH
, then you can run it as a script by just typing its name. But scripts get their own copy of the shell process, so anything they do can't affect the calling shell environment. The assignment to greeting
above will be in effect only within the script; once the script exits, it won't have had any impact on your interactive shell session:
$ hello
Setting 'greeting'
$ echo $greeting
$
Function
A function is instead defined once and stays in the shell's memory; when you call it, it executes inside the current shell, and can therefore have side effects:
hello() {
echo "Setting 'greeting'"
greeting='Hello'
}
$ hello
Setting 'greeting'
$ echo $greeting
Hello
So you use functions when you want to modify your shell environment. The Zsh Line Editor (ZLE) also uses functions - when you bind a key to some action, that action is defined as a shell function (which has to be added to ZLE with the zle -N
command).
Now, if you have a lot of functions, then you might not want to define all of them in your .zshrc
every time you start a new shell; that slows down shell startup and uses memory to store functions that you might not wind up calling during the lifetime of that shell. So you can instead put the function definitions into their own files, named after the functions they define, and put the files into directories in your $FPATH
, which works like $PATH
.
Zsh comes with a bunch of standard functions in the default $FPATH
already. But it won't know to look for a command there unless you've first told it that the command is a function.
That's essentially what autoload
does: it says "Hey, Zsh, this command name here is a function, so when I try to run it, go look for its definition in my FPATH, instead of looking for a command in my PATH."
Worth noting is that the first time you run an autoload
ed function, Zsh sources the definition file, but – unlike ksh - it does not then call the function. It's up to you to call the function inside the file after defining it so that first invocation will work. An autoload
able definition of hello
might look like this:
hello() {
echo "Setting 'greeting'"
greeting='Hello'
}
hello "$@"
$FPATH
value. (This is much like extending$PATH
in most shells.) E.g. my.zshrc
has this line:export FPATH=$HOME/dotfiles/zsh_functions:$FPATH