1

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?

  • Your forgot to post the content of greet.sh. – Gilles 'SO- stop being evil' Apr 12 '20 at 17:27
  • @Gilles'SO-stopbeingevil' They have ~/myfunctions/greet there. Does it have to have a .sh filename suffix? – Kusalananda Apr 12 '20 at 17:32
  • @Kusalananda The suffix is not relevant, but the full content of the file is. Possibly even the way the script is executed. But at the very least the file contents. – Gilles 'SO- stop being evil' Apr 12 '20 at 17:35
  • @Gilles'SO-stopbeingevil' it's there in my post, after "a file called ~/myfunctions/greet which contains:" (the contents are just those 2 lines). – RocketNuts Apr 12 '20 at 17:59
  • Oh ok. So that's not a zsh script: without a shebang line, it's an sh script. That's why I asked for the whole file. – Gilles 'SO- stop being evil' Apr 12 '20 at 18:06
  • @Gilles'SO-stopbeingevil' How do you mean without a shebang line? Isn't it just supposed to be interpreted by the default shell interpreter, which in this case is zsh? Anyway note that the script IS executed, because I can manually use greet on the shell just fine. – RocketNuts Apr 13 '20 at 08:22
  • @RocketNuts The default shell interpreter is sh, not zsh. Zsh is the default login shell on recent macOS versions, but this has nothing to do with shell scripts. This is explained in https://unix.stackexchange.com/questions/373223/which-shell-interpreter-runs-a-script-with-no-shebang – Gilles 'SO- stop being evil' Apr 13 '20 at 18:47

0 Answers0