Search code examples
environment-variablescondavirtualenvenvironment

How to execute a shell script when I activate a particular conda env?


I want a shell script, say myscript (#!/bin/sh or #!/bin/bash and it modifies PATH, PYTHONPATH and LD_LIBRARY_PATH), to be executed whenever I activate a conda env say xyz. I placed it inside ${CONDA_PREFIX}/etc/conda/activate.d/, it does not work.

I tried to put source "${CONDA_PREFIX}/etc/conda/activate.d/myscript" in ${CONDA_PREFIX}/bin/activate and found that ${CONDA_PREFIX}/bin/activate is not executed at all, even a simple echo statement at the beginning of ${CONDA_PREFIX}/bin/activate does not show anything when I activate conda activate xyz!! What to do?

Note: after activating xyz if I source ${CONDA_PREFIX}/etc/conda/activate.d/myscript it works fine. Please help.

More important: When I manually source ${CONDA_PREFIX}/etc/conda/activate.d/myscript, the cahnges are permanent, so PYTHONPATH and others remain modified even if I switch to another env. I wanted that myscript only affects within the xyz env.


Solution

  • Checklist:

    CONDA_PREFIX in ${CONDA_PREFIX}/etc/conda/activate.d is an environment to be activated. In your case it's envs/xyz in conda root directory.

    The files to be sourced must have .sh extension. In your case it must be myscript.sh

    To undo the effects of activate.d/myscript.sh you should create deactivate.d/myscript.sh. If your activate.d/myscript.sh just contains export _SOME_VAR=value your deactivate.d/myscript.sh should contain unset _SOME_VAR

    To debug activation run conda shell.bash activate xyz — the last line after the list of exports should be . CONDA_ROOT/envs/xyz/etc/conda/activate.d/myscript.sh

    I just checked this in my mini-forge installation — works as documented.