M HYPE SPLASH
// news

Why doesn't zsh autoload work in a script?

By Sarah Scott

I am trying to get to grips with autoloading functions in zsh. I have added the folder in which I'm storing my functions (~/.zfuncs) to my fpath, and I've added a test function

# ~/.zfuncs/myfunction
echo "Hello world!"

This works fine when I autoload it in my console:

stephanie% autoload -Uz myfunction
stephanie% myfunction
Hello world!

When I try to run it in a script this doesn't work:

#!/usr/bin/env zsh
# ~/scripts/test-myfunction.sh
autoload -Uz myfunction
myfunction

Running the script produces an error:

stephanie% zsh ~/scripts/test-myfunction.sh
myfunction:5: myfunction: function definition file not found

It works if I add the following line to the start of the script:

source ~/.zshrc

What am I missing or doing wrong?

1 Answer

I figured it out, with information from this answer. I needed to have the line adding my folder to fpath in my .zshenv file, not my .zshrc file, because when it's a script it's not an interactive shell.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy