Is there a command or environment variable that I can test for in my ~/.zshrc that that would differentiate between when I run source ~/.zshrc to update my configuration and when the shell reads ~/.zshrc as it's initialized?

So far my solution is to set a variable at the end of the ~/.zshrc and test for that variable on subsequent exectuion, but I'm curious if there's a cleaner way to directly get this information from the system or envrionment rather than hacking it together in a way that feels so fragile....

# somewhere in ~/.zshrc

if [[ -n $CONSOLE_ALREADY_RUNNING ]]; then
    echo "we've alredy loaded ~/.zshrc"
    echo "so you must be sourcing it"

# many more lines of ~/.zshrc commands

# last line of ~/.zshrc

Seems like there should be some cleaner way to test if I'm just reloading via source /.zshrc or if .zshrc is being executed for a new instance of zsh that was just loaded into memory.

  • Cross site duplicate: How can a zsh script test whether it is being sourced?
    – DavidPostill
    Dec 5 '16 at 16:48
  • Searching for "zsh how do i know if a script has been sourced" would have given you the answer as the second link.
    – DavidPostill
    Dec 5 '16 at 16:49
  • @DavidPostill, Thank you for your help. I searched for everything that I could think of, but I kept thinking "differentiate..." The references I found were only along the lines of: difference between source and . and all focused around bash even though I was searching for zsh... Anyway, you and Timotree have found the answer. Thank you so much to each of you!
    – erwin
    Dec 6 '16 at 4:28

$ZSH_EVAL_CONTEXT is "toplevel" if you call the script from a shell. (for example ./script) $ZSH_EVAL_CONTEXT is "toplevel:file" if you source the script. (for example source script) $ZSH_EVAL_CONTEXT is "file" if it's run automatically as a runtime configuration. (like ~/.zshrc would be.)

Found the variable here.

  • Awesome. Thank you @timotree. I thought there must be a proper way to do this.... ZSH_EVAL_CONTEXT is exactly what I was looking for, but not knowing the name I had a really difficult time finding it! My first ever Stackuser post... Thanks so much for your help!
    – erwin
    Dec 6 '16 at 4:23
  • @Ryan My pleasure! Credit also goes to DavidPostill for helping me find it.
    – timotree
    Dec 6 '16 at 4:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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