10

I want to execute Zsh function command in Bash script. Here is an example:

~/.zshrc

hello () {
  echo "Hello!"
}

hello.sh

#!/bin/bash
hello

executing above bash script in zsh

(zsh) $ ./hello.sh
hello command not found

I also tried with heredocs:

#!/bin/bash
/bin/zsh - <<'EOF'
  hello
EOF

executing above script with heredocs also says command not found error.

Any suggestions?

Thanks!

5
  • Define the function in your bash script. What's the point of calling a function defined in your .zshrc in a script? You should never do that (even in a Zsh script, unless you have valid reason). Moreover, bash and zsh are not entirely compatible, if you go deep enough. Commented Nov 12, 2015 at 7:01
  • a valid example is virtualenwrapper's workon command. even if you define the same function in bash or source it, the current zsh shell will not be reflected with the given virtual environment. Commented Nov 12, 2015 at 7:07
  • 2
    If you need the current shell environment, you either use a function (rather than a script; of course the function can be saved in a file and sourced) or pass environment variables around (or as command line arguments). Sourcing interactive init file in non-interactive script is bad practice in any case, let alone shell incompatibility issues. Commented Nov 12, 2015 at 7:13
  • makes sense, in that case, I need to make sure that my script is source-able in zsh and bash shells. Thanks! Commented Nov 12, 2015 at 7:17
  • No problem. Given that even POSIX-compatible stuff can be written (not for the faint-hearted of course...), it should be pretty easy to write code for both bash and zsh, as long as you pay attention. Commented Nov 12, 2015 at 7:28

1 Answer 1

14

You can use it like that :

#!/bin/bash

/bin/zsh -i -c hello

-i : Force shell to be interactive

Then, if the shell is interactive, commands are read from /etc/zshrc and then $ZDOTDIR/.zshrc (this is usually your $HOME/.zshrc)

-c : Run a command in this shell

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.