Ubuntu – conda activate not working in a bash file

anacondabashcommand lineconda

I am trying to write a script with the name myscrpt.sh, so when I run it it automatically creates a virtual env and activate it using conda. My conda version is 4.7.1.

This is what I have at the beginning of my myscrpt.sh:

#!/bin/bash
conda create --name myenv1
conda activate myenv1

creating the environment is not a problem, however I get the error:

CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'.
To initialize your shell, run

    $ conda init <SHELL_NAME>

Currently supported shells are:
  - bash
  - fish
  - tcsh
  - xonsh
  - zsh
  - powershell

See 'conda init --help' for more information and options.

IMPORTANT: You may need to close and restart your shell after running 'conda init'.

I don't get this error if I run conda activate myenv1 directly in my terminal.

So far I have taken several measures such as using conda init <SHELL_NAME> which did not help at all. Then I added the following in my bashrc

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

which also didnt work. Next and according to this link changed the path in the PATH line to:

. /opt/conda/etc/profile.d/conda.sh
conda activate base

This one was written for conda 4.4, but I was hoping wouold help me.

Then I tried conda run instead of conda activate, but this also did not help.

So any ideas how can I get this working? 🙂

UPDATE1: Now I use source ./myscript.sh, and activating works fine, but it gets to errors in conda install.

Best Answer

Either

  1. Add eval $(conda shell.bash hook) to your script, or
  2. Call your script with bash -i to invoke your interactive environment
Related Question