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

Josh
  • 1,744

2 Answers2

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

Moti
  • 421
  • Thanks -- Is there an equivalent mechanism for Bash? – Josh Apr 28 '14 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 '14 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.

JDonald
  • 11