Run .zshrc when passing command via -c

I have a script that runs a command via zsh -c. However, when zsh runs, it doesn’t appear to load ~/.zshrc.

I understand a login shell flag exists, but even zsh -lc <command> doesn’t seem to work.

How can I get functions, aliases, and variables defined in my ~/.zshrc to populate when running it with zsh -c?

zsh do not read .zshrc in non-interactive shell, but zsh allow you to invoke an interactive shell to run a script:

$ zsh -ic 'type f'
f is a shell function

or you can always source .zshrc manually:

$ zsh -c '. ~/.zshrc; type f'
f is a shell function
Answered By: cuonglm

While zsh doesn’t load .zshrc in non-interactive shells, as cuonglm said, it does load .zshenv. So if you’re doing setup that doesn’t require a tty, such as configuring your $PATH, that can (and probably should) be done in .zshenv.

From the zsh docs:

.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.

Answered By: thislooksfun
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.