11

I have a function in .zshrc that mostly updates the PATH:

my_function()
{
        PATH=...
}

and some scripts that depend on it, e.g. my_script.sh starts with the following lines:

my_function
# do stuff ...

I then have the following in crontab:

00 02 * * * /path/to/my/zsh /path/to/my_script.sh

but I have noticed that, even when I run my_script.sh as ./my_script.sh manually (i.e. from my interactive(?) Zsh shell), I get the error:

Command not found: my_function

even though I can perfectly invoke my_function from the terminal.

Why? I would like a solution that does not require me to add a shebang to my script (for more on this see this)

I found the following diagram. I imagine that in my case, cron launches a non-interactive, non-login shell, which is why none of the init files are run. Is that correct?

enter image description here

4
  • Is your .sh script run with a zsh interpreter? Even if you put your functions in the right place for a zsh interpreter to find them, they won't get sourced if you are using a bash interpreter to run your script.
    – jayhendren
    Apr 28, 2014 at 19:29
  • That diagram applies to bash, not to zsh. Apr 28, 2014 at 21:45
  • Thanks @Gilles. Besides references to .zshenv, do you know what else is potentially missing?
    – Josh
    Apr 28, 2014 at 22:28
  • 1
    Functions defined in a script that is executed (not sourced) will not be available after that script completes.
    – chepner
    Apr 29, 2014 at 13:22

2 Answers 2

22

Put your functions in .zshenv.

.zshenv is sourced on all invocations of the shell, unless the -f option is set. It should contain commands to set the command search path, plus other important environment variables. .zshenv should not contain commands that produce output or assume the shell is attached to a tty.

.zshrc is sourced in interactive shells. It should contain commands to set up aliases, functions, options, key bindings, etc.

http://zsh.sourceforge.net/Intro/intro_3.html

2
  • Thanks -- Is there an equivalent mechanism for Bash?
    – Josh
    Apr 28, 2014 at 19:11
  • Dont think so, what you can do is create a ".shared_functions" file and add "source /path/to/.shared_functions" to the script.
    – Moti
    Apr 28, 2014 at 19:37
1

I like to keep my shell function definitions separate from my .zshrc.

So, for what it's worth, I've had luck accessing shell functions from emacs by simply including the directory which contains my zsh functions ($HOME/.zsh) in my $PATH.

As always, YMMV.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .