Zsh: automatically set environment variables for a directory

environment-variableszsh

Let's say I have a project in:

~/working_dir

Whenever I run commands from this directory, I need to have certain environment variables set. So I can export them like so:

export VAR=value

However, there are a lot of these and it gets tedious, plus I forget sometimes and run a command only to have it fail because it's missing the environment variables that give it API keys or something.

Is there a way I can get zsh to remember these environment variables for this directory, so that any time I run any command from that directory it runs with those environment variables set?

Best Answer

It's possible to do this - here's a screencast, using the Grml ZSH configuration.

Further information:

Edit: This is actually pretty easy to do. Here's the relevant portion of your ~/.zshrc:

function chpwd_profiles() {
    local profile context
    local -i reexecute

    context=":chpwd:profiles:$PWD"
    zstyle -s "$context" profile profile || profile='default'
    zstyle -T "$context" re-execute && reexecute=1 || reexecute=0

    if (( ${+parameters[CHPWD_PROFILE]} == 0 )); then
        typeset -g CHPWD_PROFILE
        local CHPWD_PROFILES_INIT=1
        (( ${+functions[chpwd_profiles_init]} )) && chpwd_profiles_init
    elif [[ $profile != $CHPWD_PROFILE ]]; then
        (( ${+functions[chpwd_leave_profile_$CHPWD_PROFILE]} )) \
            && chpwd_leave_profile_${CHPWD_PROFILE}
    fi  
    if (( reexecute )) || [[ $profile != $CHPWD_PROFILE ]]; then
        (( ${+functions[chpwd_profile_$profile]} )) && chpwd_profile_${profile}
    fi  

    CHPWD_PROFILE="${profile}"
    return 0
}
# Add the chpwd_profiles() function to the list called by chpwd()!
chpwd_functions=( ${chpwd_functions} chpwd_profiles )

Activate the profile for each directory you want:

zstyle ':chpwd:profiles:/path/to/directory(|/|/*)' profile NAME

And don't forget to actually make a profile:

chpwd_profile_NAME() {
    [[ ${profile} == ${CHPWD_PROFILE} ]] && return 1
    print "chpwd(): Switching to profile: $profile"

    export VAR=value
}

Edit #2: This would actually be rather neat to couple with named directories [Stackoverflow.net].

Related Question