QnA
QnA

Reputation: 1103

How does `conda activate` change *current* bash environment?

If I want to change my current bash env variables by executing a shell script, I need to do source somecript, so that the env setting commands are run in current bash rather than a forked one.

conda itself is a python script, and by just running conda activate someenv on the command line, bash itself is forked first. If that is the case, how come after execution of this command, my original bash env variable were set?

I tried to dig into the conda package but wan't able to find how this is done before getting lost...

Upvotes: 4

Views: 1629

Answers (1)

FlyingTeller
FlyingTeller

Reputation: 20472

conda itself is a python script

I don't know where you have read this. conda is set up as a bash function, which you can verify yourself. In the .bashrc you can see that the file /miniconda3/etc/profile.d/conda.sh is called to set up the conda command, which looks like this:

conda() {
    if [ "$#" -lt 1 ]; then
        "$CONDA_EXE" $_CE_M $_CE_CONDA
    else
        \local cmd="$1"
        shift
        case "$cmd" in
            activate|deactivate)
                __conda_activate "$cmd" "$@"
                ;;
            install|update|upgrade|remove|uninstall)
                CONDA_INTERNAL_OLDPATH="${PATH}"
                __add_sys_prefix_to_path
                "$CONDA_EXE" $_CE_M $_CE_CONDA "$cmd" "$@"
                \local t1=$?
                PATH="${CONDA_INTERNAL_OLDPATH}"
                if [ $t1 = 0 ]; then
                    __conda_reactivate
                else
                    return $t1
                fi
                ;;
            *)
                CONDA_INTERNAL_OLDPATH="${PATH}"
                __add_sys_prefix_to_path
                "$CONDA_EXE" $_CE_M $_CE_CONDA "$cmd" "$@"
                \local t1=$?
                PATH="${CONDA_INTERNAL_OLDPATH}"
                return $t1
                ;;
        esac
    fi
}

and calls the __add_sys_prefix_to_path function to modify the PATH:

__add_sys_prefix_to_path() {
    # In dev-mode CONDA_EXE is python.exe and on Windows
    # it is in a different relative location to condabin.
    if [ -n "${_CE_CONDA}" ] && [ -n "${WINDIR+x}" ]; then
        SYSP=$(\dirname "${CONDA_EXE}")
    else
        SYSP=$(\dirname "${CONDA_EXE}")
        SYSP=$(\dirname "${SYSP}")
    fi

    if [ -n "${WINDIR+x}" ]; then
        PATH="${SYSP}/bin:${PATH}"
        PATH="${SYSP}/Scripts:${PATH}"
        PATH="${SYSP}/Library/bin:${PATH}"
        PATH="${SYSP}/Library/usr/bin:${PATH}"
        PATH="${SYSP}/Library/mingw-w64/bin:${PATH}"
        PATH="${SYSP}:${PATH}"
    else
        PATH="${SYSP}/bin:${PATH}"
    fi
    \export PATH
}

so conda doesn't launch any sub bash shells, but is just a (series) of bash functions, which simply edit the current env variable in place

Upvotes: 4

Related Questions