6

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"
fi

# many more lines of ~/.zshrc commands

# last line of ~/.zshrc
export CONSOLE_ALREADY_RUNNING=1

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.

erwin
  • 194
  • 9
  • Cross site duplicate: [How can a zsh script test whether it is being sourced?](//unix.stackexchange.com/q/73008) – DavidPostill Dec 05 '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 05 '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 06 '16 at 04:28

1 Answers1

6

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

timotree
  • 1,078
  • 1
  • 9
  • 22
  • 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 06 '16 at 04:23
  • @Ryan My pleasure! Credit also goes to DavidPostill for helping me find it. – timotree Dec 06 '16 at 04:24