Unable to activate environment - prompted to Run 'conda init' before 'conda activate' but it doesn't work

I spent some time digging into this and I think I understand why this happens - or maybe one of the reasons this happens. The first thing I had to understand is that the conda init code that generally gets automatically added to your ~/.bashrc and looks something like this:

# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$('/path-to-conda/bin/conda' 'shell.bash' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
    eval "$__conda_setup"
else
    if [ -f "/path-to-conda/etc/profile.d/conda.sh" ]; then
        . "/path-to-conda/etc/profile.d/conda.sh"
    else
        export PATH="/path-to-conda/bin:$PATH"
    fi
fi
unset __conda_setup
# <<< conda initialize <<<

Has to be run in every shell whether it’s a login shell or a sub-shell (say an xterm launched by your window manager). That means:

  • The “conda init” code has to be in your SHELL’s init file (e.g. ~/.bashrc, ~/.cshrc, etc) and not in a login init file (e.g. ~/.profile, ~/.bash_profile, etc). Those login init files only get executed once when you first log in (unless you explicitly set the -l flag which you shouldn’t generally do).
  • The “conda init” code has to be executed no matter how the shell was invoked. What I mean is that the init code should occur before any statement like the following snippet below in your SHELL’s init file. Note that the following code is in every default Ubuntu ~/.bashrc I’ve seen recently and causes the rest of the init file to be ignored if the shell is not interactive (for example in any bash script).
# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac
  • Whenever you run conda init, the conda init code is automatically added to the end of your SHELL’s init file which means it won’t get executed by a default Ubuntu ~/.bashrc file if the shell is not interactive.

All this causes problems if you are writing scripts that require a specific environment. For example, if myscript.sh looks like this:

#! /bin/bash -e

# First I need to make sure I'm using the right environment:
conda activate task-specific-env

python /some-path/task-specific-script.py

It will fail if the conda init code is not executed for non-interactive shells.