Source my .zshrc in a bash script

7k Views Asked by At

Lets say I have this bash script (test):

#!/usr/bin/env bash
source ~/.zshrc

In my .zshrc, I have the following:

autoload -U compinit
compinit

When I try and run 'bash test' from my terminal window (zsh), I get errors saying autoload and compinit commands are not found. If I just do source ~/.zshrc from the command line, it works fine.

I am trying to setup my development environment, similar to this blog, but when the scripts try and source the .zshrc file it fails.

Any insight would be appreciated.

2

There are 2 best solutions below

0
On

In your script, you're using bash to run a zsh script. You might as well ask the python interpreter to parse perl.

Either change bash to zsh in the shebang line or write the script with bash commands.

1
On

It's not quite as bad as python vs. perl. Both bash and zsh are derived from the Bourne shell (whose behavior is standardized by POSIX), so any script designed to work with /bin/sh is likely to work with either bash or zsh.

Normally your ~/.zshrc, as the name implies, is designed to be used with zsh, and will typically include zsh-specific commands like autoload and compinit.

You can make those commands conditional, for example:

if [ "$ZSH_VERSION" ] ; then
    autoload -U compinit
    compinit
fi

But of course that means you won't get the functionality of those commands, unless you can figure out a way to emulate them in bash. (I'm not familiar with either command, so I can't help you there.)

(Note that this will fail if you've done set -u or set -o nounset in your bash shell.)

But if you're going to be using both zsh and bash, it probably makes a lot more sense to have separate ~/.bashrc and ~/.zshrc files, and use each one only with the shell for which it's designed. If you want to avoid duplication, each one can source a third file containing common commands.

(And based on the comments, it's likely you're doing the wrong thing in the first place.)