Search code examples
zshoh-my-zsh

Conditionally source a script in zsh


I currently source an initializations script in my .zshrc. Unfortunately this makes some modifications to my environment and $PATH I don't want, unless I'm in some specific directories.

Sure, I could compare the output of pwd with the current dir, but I would like to source if I'm in a specific directory or one of its subdirectories at any level.

And is there probably an entirely different solution to my problem?


Solution

  • Using a child process just to run pwd is overkill. You find your current directory always stored in the variable PWD. This variable is maintained automatically by zsh.

    You can find whether your working directory is in or below a certain directory dir by

    if [[ $PWD:A == $dir:A || $PWD:A == $dir:A/** ]]
    then
      # I am in $dir or below it
      ...
    fi
    

    The :A takes care of the cases where one of the path components involved in the comparision happens to be a symlink. I'm not sure whether you will need this for PWD, but it does not harm using it.