Search code examples
condaminiconda

How to init miniconda with a managed bashrc?


I have a single .bashrc that works for bash & zsh on Mac, Windows (msys and WSL) and Linux. I distribute it with git and some scripts. It seems hard to use miniconda that way; it wants to write some system-specific paths into my .bashrc which I'd prefer not to do. It also has its own "block" with special comments so I know it might be overwritten which I'd also prefer it not to do.

On Linux it installs this block:

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

Is anyone using miniconda in an environment like this? What's the best way to approach this? Maybe put all the miniconda init code into a separate system-specific conda-init.sh created from what conda init would produce, and source that? Then as long as I don't accidentally run conda init (which would re-add the removed lines) I'd be OK.

Or maybe I should copy all the conda init code variants (for all OSes) into my big bashrc and wrap the calls with OS tests so it calls the right one? Removing the special >>> conda initialize >>> comment block so it doesn't get overwritten of course? That seems like a maintenance nightmare.

Or maybe as a variant of that, look at all the variants and see if I can make a nice version that runs everywhere? In fact, wouldn't it be nice if miniconda shipped that, so I could just source it? Maybe it does?

Ideally I'd like it to be as simple as the init code for direnv which is just eval $(direnv hook $SHELL) once direnv is in $PATH. It seems like the first few lines of the script above are basically that; could I just call that and skip the else conditions?


Solution

  • If you can guarantee that ${CONDA_ROOT}/condabin will be on PATH, then you could probably get away with only:

    eval "$('conda' 'shell.posix' 'hook')"
    

    That is, it sounds like POSIX is sufficiently generic to cover the shells. I can at least attest it works on bash and zsh on macOS.