3

Currently my ZSH has some sourced functions, for instance:

% declare -f
     ... a lot of shell functions appears here.

I'm currently writing a shell script that will call a specific function from that list (prompt_dir from Powerlevel9k's theme for Oh-My-Zsh).

My script is:

#!/bin/zsh
echo_prompt_segment(){
    # bunch of source-code here
}

zsh_oddeven_dir(){
   prompt_dir echo
}

zsh_oddeven_dir

Problem is that my script cannot access these functions:

% ./oddeven-pwd.sh
zsh_oddeven_dir:1: command not found: prompt_dir

When I do declare -f from inside the script, there are only those two functions that's inside my script:

% ./oddeven-pwd.sh 
echo_prompt_segment () {

}
zsh_oddeven_dir () {
    declare -f
}

Can I access and run those functions that were declared above my script? If so, how?

1
  • Please, do not add a solution to the question body. You can answer your own question in the answer field. The text of your solution is still available here so you don't need to retype. Also adding "SOLVED" to the title is not what we do on Super User. Accepting an answer is enough to indicate the problem is solved. Commented Jun 4, 2018 at 22:36

1 Answer 1

2

Since by default scripts run in subshells, the facility you require is exported functions, available in bash, but not in zsh.

In bash the standard place to add user functions is in ~/.bashrc, but this is not executed unless bash is interactive (specifically, not in a subshell running a script), which exported functions overcome.

What does seem to work, as per this answer, is to put your function declarations in ~/.zshenv, which is executed by default on every launch, interactive or not.

You should also look at the previous (accepted) answer, which among other things explains the reason that zsh does not support exported functions.

2
  • Well, the previous accepted answer directed me by actually seeing the actual problem: independently of bash or zsh (actually either my script and the function declaration were in zsh), when I run my script, it runs in a separated shell process, so it loses function references. I solved the problem using source myscript.sh instead of normally running it.
    – Diego S.
    Commented Jun 4, 2018 at 17:53
  • Sorry, I should have made the point that scripts by default run in subshells. I am so used to the idea that I forget that not everyone is aware of it. I have expanded my answer to explain this, with some salient points about how shells are initialised
    – AFH
    Commented Jun 4, 2018 at 21:42

You must log in to answer this question.

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