Skip to main content
edited tags
Link
Gilles 'SO- stop being evil'
  • 866.5k
  • 205
  • 1.8k
  • 2.3k
Source Link
RocketNuts
  • 419
  • 1
  • 5
  • 12

How to define global functions in zsh (macOS) that are available in scripts?

Since macOS 10.15 (Catalina) the default shell has changed from bash to zsh. One of the things I'm running into is I cannot get my own global functions working. I used to export these from .bash_profile but zsh doesn't seem to know the concept of exporting functions.

Say I have this:

function greet { echo "Hello $1, how are you today" }

If I then run hello RocketNuts on the shell, it says Hello RocketNuts, how are you today. So far so good.

Now I want to make this function global so that it's also available in scripts.

I have tried:

  • putting it in .zshrc
  • putting it in .zshenv

I also tried creating a subdir ~/myfunctions and a file called ~/myfunctions/greet which contains:

function greet { echo "Hello $1, how are you today" } greet "$@" 

and then in either ~/.zshrc or ~/.zshenv I add:

fpath=( ~/myfunctions "${fpath[@]}" ) autoload -Uz greet 

However, none of these methods make the greet function available in scripts.

From the shell, they all work fine. With either method, I can invoke the greet function manually on the shell.

But if I have a file test.sh which does greet Somebody and run that, it always says "greet: command not found".

How do I get this working in zsh?