Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

share|improve this question
    
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 at 19:29
    
That diagram applies to bash, not to zsh. –  Gilles Apr 28 at 21:45
    
Thanks @Gilles. Besides references to .zshenv, do you know what else is potentially missing? –  Josh Apr 28 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 at 13:22

1 Answer 1

up vote 4 down vote accepted

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

share|improve this answer
    
Thanks -- Is there an equivalent mechanism for Bash? –  Josh Apr 28 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 at 19:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.