Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't execute conda activate from bash script #7980

Open
Tracked by #11308
mjspeck opened this issue Nov 20, 2018 · 117 comments
Open
Tracked by #11308

Can't execute conda activate from bash script #7980

mjspeck opened this issue Nov 20, 2018 · 117 comments
Labels
backlog issue has been triaged but has not been earmarked for any upcoming release cli pertains to the CLI interface good first issue great for new contributors, code change is envisioned to be trivial/relatively straight-forward severity::3 major; broken functionality with a workaround source::community catch-all for issues filed by community members type::bug describes erroneous operation, use severity::* to classify the type

Comments

@mjspeck
Copy link

mjspeck commented Nov 20, 2018

Current Behavior

Trying to use conda activate my_env does not work inside a bash script. The workaround is to use source activate my_env but this shouldn't be necessary.

Steps to Reproduce

Write a bash script with the following code inside, let's call it my-script.sh:

conda activate my_env

When you run ./my-script.sh, you get the following output:

CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'.
If your shell is Bash or a Bourne variant, enable conda for the current user with

    $ echo ". /Users/matthewspeck/anaconda3/etc/profile.d/conda.sh" >> ~/.bash_profile

or, for all users, enable conda with

    $ sudo ln -s /Users/matthewspeck/anaconda3/etc/profile.d/conda.sh /etc/profile.d/conda.sh

The options above will permanently enable the 'conda' command, but they do NOT
put conda's base (root) environment on PATH.  To do so, run

    $ conda activate

in your terminal, or to put the base environment on PATH permanently, run

    $ echo "conda activate" >> ~/.bash_profile

Previous to conda 4.4, the recommended way to activate conda was to modify PATH in
your ~/.bash_profile file.  You should manually remove the line that looks like

    export PATH="/Users/matthewspeck/anaconda3/bin:$PATH"

^^^ The above line should NO LONGER be in your ~/.bash_profile file! ^^^

However, conda is in fact installed correctly, and runs fine in the command line.

The command which conda returns the following:

conda () {
	if [ "$#" -lt 1 ]
	then
		$_CONDA_EXE
	else
		\local cmd="$1"
		shift
		case "$cmd" in
			(activate) _conda_activate "$@" ;;
			(deactivate) _conda_deactivate "$@" ;;
			(install | update | uninstall | remove) $_CONDA_EXE "$cmd" "$@" && _conda_reactivate ;;
			(*) $_CONDA_EXE "$cmd" "$@" ;;
		esac
	fi
}

Expected Behavior

conda should activate in a bash script the same way it does on the command line.

Environment Information

`conda info`


     active environment : base
    active env location : /Users/matthewspeck/anaconda3
            shell level : 1
       user config file : /Users/matthewspeck/.condarc
 populated config files : /Users/matthewspeck/.condarc
          conda version : 4.5.11
    conda-build version : 3.16.2
         python version : 3.6.6.final.0
       base environment : /Users/matthewspeck/anaconda3  (writable)
           channel URLs : https://repo.anaconda.com/pkgs/main/osx-64
                          https://repo.anaconda.com/pkgs/main/noarch
                          https://repo.anaconda.com/pkgs/free/osx-64
                          https://repo.anaconda.com/pkgs/free/noarch
                          https://repo.anaconda.com/pkgs/r/osx-64
                          https://repo.anaconda.com/pkgs/r/noarch
                          https://repo.anaconda.com/pkgs/pro/osx-64
                          https://repo.anaconda.com/pkgs/pro/noarch
          package cache : /Users/matthewspeck/anaconda3/pkgs
                          /Users/matthewspeck/.conda/pkgs
       envs directories : /Users/matthewspeck/anaconda3/envs
                          /Users/matthewspeck/.conda/envs
               platform : osx-64
             user-agent : conda/4.5.11 requests/2.20.0 CPython/3.6.6 Darwin/17.7.0 OSX/10.13.6
                UID:GID : 501:20
             netrc file : None
           offline mode : False

`conda config --show-sources`

==> /Users/matthewspeck/.condarc <==
ssl_verify: True
channels:
  - defaults

`conda list --show-channel-urls`

# packages in environment at /Users/matthewspeck/anaconda3:
#
# Name                    Version                   Build  Channel
_ipyw_jlab_nb_ext_conf    0.1.0                    py36_0    defaults
alabaster                 0.7.12                   py36_0    defaults
anaconda-client           1.7.2                    py36_0    defaults
anaconda-navigator        1.9.2                    py36_0    defaults
anaconda-project          0.8.2                    py36_0    defaults
appdirs                   1.4.3            py36h28b3542_0    defaults
appnope                   0.1.0            py36hf537a9a_0    defaults
appscript                 1.0.1            py36h1de35cc_1    defaults
asn1crypto                0.24.0                   py36_0    defaults
astroid                   2.0.4                    py36_0    defaults
astropy                   3.0.5            py36h1de35cc_0    defaults
atomicwrites              1.2.1                    py36_0    defaults
attrs                     18.2.0           py36h28b3542_0    defaults
automat                   0.7.0                    py36_0    defaults
babel                     2.6.0                    py36_0    defaults
backcall                  0.1.0                    py36_0    defaults
backports                 1.0                      py36_1    defaults
backports.os              0.1.1                    py36_0    defaults
backports.shutil_get_terminal_size 1.0.0                    py36_2    defaults
beautifulsoup4            4.6.3                    py36_0    defaults
bitarray                  0.8.3            py36h1de35cc_0    defaults
bkcharts                  0.2              py36h073222e_0    defaults
blas                      1.0                         mkl    defaults
blaze                     0.11.3                   py36_0    defaults
bleach                    3.0.2                    py36_0    defaults
blosc                     1.14.4               hd9629dc_0    defaults
bokeh                     1.0.1                    py36_0    defaults
boto                      2.49.0                   py36_0    defaults
bottleneck                1.2.1            py36h1d22016_1    defaults
bzip2                     1.0.6                h1de35cc_5    defaults
ca-certificates           2018.03.07                    0    defaults
certifi                   2018.10.15               py36_0    defaults
cffi                      1.11.5           py36h6174b99_1    defaults
chardet                   3.0.4                    py36_1    defaults
click                     7.0                      py36_0    defaults
cloudpickle               0.6.1                    py36_0    defaults
clyent                    1.2.2                    py36_1    defaults
colorama                  0.4.0                    py36_0    defaults
conda                     4.5.11                   py36_0    defaults
conda-build               3.16.2                   py36_0    defaults
conda-env                 2.6.0                         1    defaults
constantly                15.1.0           py36h28b3542_0    defaults
contextlib2               0.5.5            py36hd66e5e7_0    defaults
coverage                  4.5.1            py36h1de35cc_0    defaults
cryptography              2.3.1            py36hdbc3d79_0    defaults
curl                      7.61.0               ha441bb4_0    defaults
cycler                    0.10.0           py36hfc81398_0    defaults
cython                    0.29             py36h0a44026_0    defaults
cytoolz                   0.9.0.1          py36h1de35cc_1    defaults
dask                      0.20.0                   py36_0    defaults
dask-core                 0.20.0                   py36_0    defaults
datashape                 0.5.4                    py36_1    defaults
dbus                      1.13.2               h760590f_1    defaults
decorator                 4.3.0                    py36_0    defaults
defusedxml                0.5.0                    py36_1    defaults
distributed               1.24.0                   py36_0    defaults
docutils                  0.14             py36hbfde631_0    defaults
entrypoints               0.2.3                    py36_2    defaults
et_xmlfile                1.0.1            py36h1315bdc_0    defaults
expat                     2.2.6                h0a44026_0    defaults
fastcache                 1.0.2            py36h1de35cc_2    defaults
filelock                  3.0.10                   py36_0    defaults
flask                     1.0.2                    py36_1    defaults
flask-cors                3.0.6                    py36_0    defaults
freetype                  2.9.1                hb4e5f40_0    defaults
get_terminal_size         1.0.0                h7520d66_0    defaults
gettext                   0.19.8.1             h15daf44_3    defaults
gevent                    1.3.7            py36h1de35cc_1    defaults
glib                      2.56.2               hd9629dc_0    defaults
glob2                     0.6                      py36_1    defaults
gmp                       6.1.2                hb37e062_1    defaults
gmpy2                     2.0.8            py36h6ef4df4_2    defaults
greenlet                  0.4.15           py36h1de35cc_0    defaults
h5py                      2.8.0            py36h878fce3_3    defaults
hdf5                      1.10.2               hfa1e0ec_1    defaults
heapdict                  1.0.0                    py36_2    defaults
html5lib                  1.0.1                    py36_0    defaults
hyperlink                 18.0.0                   py36_0    defaults
icu                       58.2                 h4b95b61_1    defaults
idna                      2.7                      py36_0    defaults
imageio                   2.4.1                    py36_0    defaults
imagesize                 1.1.0                    py36_0    defaults
importlib_metadata        0.6                      py36_0    defaults
incremental               17.5.0                   py36_0    defaults
intel-openmp              2019.0                      118    defaults
ipykernel                 5.1.0            py36h39e3cac_0    defaults
ipython                   7.1.1            py36h39e3cac_0    defaults
ipython_genutils          0.2.0            py36h241746c_0    defaults
ipywidgets                7.4.2                    py36_0    defaults
isort                     4.3.4                    py36_0    defaults
itsdangerous              1.1.0                    py36_0    defaults
jbig                      2.1                  h4d881f8_0    defaults
jdcal                     1.4                      py36_0    defaults
jedi                      0.13.1                   py36_0    defaults
jinja2                    2.10                     py36_0    defaults
jpeg                      9b                   he5867d9_2    defaults
jsonschema                2.6.0            py36hb385e00_0    defaults
jupyter                   1.0.0                    py36_7    defaults
jupyter_client            5.2.3                    py36_0    defaults
jupyter_console           6.0.0                    py36_0    defaults
jupyter_core              4.4.0                    py36_0    defaults
jupyterlab                0.35.3                   py36_0    defaults
jupyterlab_launcher       0.13.1                   py36_0    defaults
jupyterlab_server         0.2.0                    py36_0    defaults
keyring                   16.0.0                   py36_0    defaults
kiwisolver                1.0.1            py36h0a44026_0    defaults
lazy-object-proxy         1.3.1            py36h1de35cc_2    defaults
libarchive                3.3.3                hc2e69e3_1    defaults
libcurl                   7.61.0               hf30b1f0_0    defaults
libcxx                    4.0.1                h579ed51_0    defaults
libcxxabi                 4.0.1                hebd6815_0    defaults
libedit                   3.1.20170329         hb402a30_2    defaults
libffi                    3.2.1                h475c297_4    defaults
libgfortran               3.0.1                h93005f0_2    defaults
libiconv                  1.15                 hdd342a3_7    defaults
libpng                    1.6.34               he12f830_0    defaults
libsodium                 1.0.16               h3efe00b_0    defaults
libssh2                   1.8.0                h322a93b_4    defaults
libtiff                   4.0.9                hcb84e12_2    defaults
libxml2                   2.9.8                hab757c2_1    defaults
libxslt                   1.1.32               hb819dd2_0    defaults
llvmlite                  0.25.0           py36h8c7ce04_0    defaults
locket                    0.2.0            py36hca03003_1    defaults
lxml                      4.2.5            py36hef8c89e_0    defaults
lz4-c                     1.8.1.2              h1de35cc_0    defaults
lzo                       2.10                 h362108e_2    defaults
markupsafe                1.0              py36h1de35cc_1    defaults
matplotlib                3.0.0            py36h54f8f79_0    defaults
mccabe                    0.6.1                    py36_1    defaults
mistune                   0.8.4            py36h1de35cc_0    defaults
mkl                       2019.0                      118    defaults
mkl-service               1.1.2            py36h6b9c3cc_5    defaults
mkl_fft                   1.0.6            py36hb8a8100_0    defaults
mkl_random                1.0.1            py36h5d10147_1    defaults
more-itertools            4.3.0                    py36_0    defaults
mpc                       1.1.0                h6ef4df4_1    defaults
mpfr                      4.0.1                h3018a27_3    defaults
mpmath                    1.0.0                    py36_2    defaults
msgpack-python            0.5.6            py36h04f5b5a_1    defaults
multipledispatch          0.6.0                    py36_0    defaults
navigator-updater         0.2.1                    py36_0    defaults
nbconvert                 5.4.0                    py36_1    defaults
nbformat                  4.4.0            py36h827af21_0    defaults
ncurses                   6.1                  h0a44026_0    defaults
networkx                  2.2                      py36_1    defaults
nltk                      3.3.0                    py36_0    defaults
nose                      1.3.7                    py36_2    defaults
notebook                  5.7.0                    py36_0    defaults
numba                     0.40.0           py36h6440ff4_0    defaults
numexpr                   2.6.8            py36h1dc9127_0    defaults
numpy                     1.15.4           py36h6a91979_0    defaults
numpy-base                1.15.4           py36h8a80b8c_0    defaults
numpydoc                  0.8.0                    py36_0    defaults
odo                       0.5.1            py36hc1af34a_0    defaults
olefile                   0.46                     py36_0    defaults
openpyxl                  2.5.9                    py36_0    defaults
openssl                   1.0.2p               h1de35cc_0    defaults
packaging                 18.0                     py36_0    defaults
pandas                    0.23.4           py36h6440ff4_0    defaults
pandoc                    1.19.2.1             ha5e8f32_1    defaults
pandocfilters             1.4.2                    py36_1    defaults
parso                     0.3.1                    py36_0    defaults
partd                     0.3.9                    py36_0    defaults
path.py                   11.5.0                   py36_0    defaults
pathlib2                  2.3.2                    py36_0    defaults
patsy                     0.5.1                    py36_0    defaults
pcre                      8.42                 h378b8a2_0    defaults
pep8                      1.7.1                    py36_0    defaults
pexpect                   4.6.0                    py36_0    defaults
pickleshare               0.7.5                    py36_0    defaults
pillow                    5.3.0            py36hb68e598_0    defaults
pip                       18.1                     py36_0    defaults
pkginfo                   1.4.2                    py36_1    defaults
pluggy                    0.8.0                    py36_0    defaults
ply                       3.11                     py36_0    defaults
prometheus_client         0.4.2                    py36_0    defaults
prompt_toolkit            2.0.7                    py36_0    defaults
psutil                    5.4.8            py36h1de35cc_0    defaults
ptyprocess                0.6.0                    py36_0    defaults
py                        1.7.0                    py36_0    defaults
pyasn1                    0.4.4            py36h28b3542_0    defaults
pyasn1-modules            0.2.2                    py36_0    defaults
pycodestyle               2.4.0                    py36_0    defaults
pycosat                   0.6.3            py36h1de35cc_0    defaults
pycparser                 2.19                     py36_0    defaults
pycrypto                  2.6.1            py36h1de35cc_9    defaults
pycurl                    7.43.0.2         py36hdbc3d79_0    defaults
pyflakes                  2.0.0                    py36_0    defaults
pygments                  2.2.0            py36h240cd3f_0    defaults
pylint                    2.1.1                    py36_0    defaults
pyodbc                    4.0.24           py36h0a44026_0    defaults
pyopenssl                 18.0.0                   py36_0    defaults
pyparsing                 2.3.0                    py36_0    defaults
pyqt                      5.9.2            py36h655552a_2    defaults
pysocks                   1.6.8                    py36_0    defaults
pytables                  3.4.4            py36h13cba08_0    defaults
pytest                    3.10.0                   py36_0    defaults
pytest-arraydiff          0.2              py36h39e3cac_0    defaults
pytest-astropy            0.4.0                    py36_0    defaults
pytest-cov                2.6.0                    py36_0    defaults
pytest-doctestplus        0.1.3                    py36_0    defaults
pytest-openfiles          0.3.0                    py36_0    defaults
pytest-remotedata         0.3.1                    py36_0    defaults
python                    3.6.6                hc167b69_0    defaults
python-dateutil           2.7.5                    py36_0    defaults
python-libarchive-c       2.8                      py36_6    defaults
python.app                2                        py36_9    defaults
pytz                      2018.7                   py36_0    defaults
pywavelets                1.0.1            py36h1d22016_0    defaults
pyyaml                    3.13             py36h1de35cc_0    defaults
pyzmq                     17.1.2           py36h1de35cc_0    defaults
qt                        5.9.6                h45cd832_2    defaults
qtawesome                 0.5.2                    py36_0    defaults
qtconsole                 4.4.2                    py36_0    defaults
qtpy                      1.5.2                    py36_0    defaults
readline                  7.0                  h1de35cc_5    defaults
requests                  2.20.0                   py36_0    defaults
rope                      0.11.0                   py36_0    defaults
ruamel_yaml               0.15.46          py36h1de35cc_0    defaults
scikit-image              0.14.0           py36h0a44026_1    defaults
scikit-learn              0.20.0           py36h4f467ca_1    defaults
scipy                     1.1.0            py36h28f7352_1    defaults
seaborn                   0.9.0                    py36_0    defaults
send2trash                1.5.0                    py36_0    defaults
service_identity          17.0.0           py36h28b3542_0    defaults
setuptools                40.5.0                   py36_0    defaults
simplegeneric             0.8.1                    py36_2    defaults
singledispatch            3.4.0.3          py36hf20db9d_0    defaults
sip                       4.19.8           py36h0a44026_0    defaults
six                       1.11.0                   py36_1    defaults
snappy                    1.1.7                he62c110_3    defaults
snowballstemmer           1.2.1            py36h6c7b616_0    defaults
sortedcollections         1.0.1                    py36_0    defaults
sortedcontainers          2.0.5                    py36_0    defaults
sphinx                    1.8.1                    py36_0    defaults
sphinxcontrib             1.0                      py36_1    defaults
sphinxcontrib-websupport  1.1.0                    py36_1    defaults
spyder                    3.3.1                    py36_1    defaults
spyder-kernels            0.2.6                    py36_0    defaults
sqlalchemy                1.2.13           py36h1de35cc_0    defaults
sqlite                    3.24.0               ha441bb4_0    defaults
statsmodels               0.9.0            py36h1d22016_0    defaults
sympy                     1.3                      py36_0    defaults
tblib                     1.3.2            py36hda67792_0    defaults
terminado                 0.8.1                    py36_1    defaults
testpath                  0.4.2                    py36_0    defaults
tk                        8.6.8                ha441bb4_0    defaults
toolz                     0.9.0                    py36_0    defaults
tornado                   5.1.1            py36h1de35cc_0    defaults
tqdm                      4.28.1           py36h28b3542_0    defaults
traitlets                 4.3.2            py36h65bd3ce_0    defaults
twisted                   17.5.0                   py36_0    defaults
typed-ast                 1.1.0            py36h1de35cc_0    defaults
unicodecsv                0.14.1           py36he531d66_0    defaults
unixodbc                  2.3.7                h1de35cc_0    defaults
urllib3                   1.23                     py36_0    defaults
virtualenv                16.1.0                    <pip>
wcwidth                   0.1.7            py36h8c6ec74_0    defaults
webencodings              0.5.1                    py36_1    defaults
werkzeug                  0.14.1                   py36_0    defaults
wheel                     0.32.2                   py36_0    defaults
widgetsnbextension        3.4.2                    py36_0    defaults
wrapt                     1.10.11          py36h1de35cc_2    defaults
xlrd                      1.1.0                    py36_1    defaults
xlsxwriter                1.1.2                    py36_0    defaults
xlwings                   0.14.0                   py36_0    defaults
xlwt                      1.2.0            py36h5ad1178_0    defaults
xz                        5.2.4                h1de35cc_4    defaults
yaml                      0.1.7                hc338f04_2    defaults
zeromq                    4.2.5                h0a44026_1    defaults
zict                      0.1.3                    py36_0    defaults
zlib                      1.2.11               hf3cbc9b_2    defaults
zope                      1.0                      py36_1    defaults
zope.interface            4.6.0            py36h1de35cc_0    defaults
zstd                      1.3.3                h2a6be3a_0    defaults

@nehaljwani
Copy link
Contributor

nehaljwani commented Nov 24, 2018

Functions are not exported by default to be made available in subshells. I'd recommend you do:

source ~/anaconda3/etc/profile.d/conda.sh
conda activate my_env

Closing as non-issue. Feel free to re-open if you feel otherwise.

******* EDIT *******
In the commands above, replace ~/anaconda3/ with the path to your miniconda / anaconda installation. You can find that out by running: conda info | grep -i 'base environment'

@mforbes
Copy link

mforbes commented Feb 23, 2019

@nehaljwani How would you do this, for example, in a makefile, and is there a simple way to get the path to conda.sh programmatically (say from the name of the environment or an environment.yml file)?

@rbutleriii
Copy link

That seems a messy solution to the issue. Now there is a source line in your bash scripts that has to explicitly reference your conda installation path, making them not very portable.

If you use something like source $CONDA_PREFIX/etc/profile.d/conda.sh to get around this, it then makes the script error in everything but the base environment. You could comment in your script that it can only be run from the base, but again: messy.

Is there a conda variable that always returns your base path regardless of your current location?

@stuarteberg
Copy link
Contributor

stuarteberg commented Mar 13, 2019

@rbutleriii

Is there a conda variable that always returns your base path regardless of your current location?

Try this:

CONDA_BASE=$(conda info --base)

@stuarteberg
Copy link
Contributor

stuarteberg commented Mar 13, 2019

@nehaljwani When conda is installed and a user's .bashrc is modified, should the following lines be added to .bashrc? That might save the users some headache. It enables conda to be called from bash scripts without sourcing $(conda info --base)/etc/profile.d/conda.sh.

export -f conda
export -f __conda_activate
export -f __conda_reactivate
export -f __conda_hashr

@shenweihai1
Copy link

Functions are not exported by default to be made available in subshells. I'd recommend you do:

source ~/anaconda3/etc/profile.d/conda.sh
conda activate my_env

Closing as non-issue. Feel free to re-open if you feel otherwise.

that works perfectly~!!!

@kagemusha
Copy link

I'm trying that, but get:

➜  /Users/michael  source ~/miniconda3/etc/profile.d/conda.sh
/Users/michael/miniconda3/etc/profile.d/conda.sh:30: parse error near `}'

I'm on Mojave and installed with Miniconda3-latest-MacOSX-x86_64.pkg

@jasonsydes
Copy link

This is not a non-issue @nehaljwani. As a user, I would expect that when I run "conda init", that it would prepare my shell for use of "conda activate" everywhere, including within scripts. But it doesn't.

The expected behavior should be exactly what @mjspeck specified, namely that "conda should activate in a bash script the same way it does on the command line".

@rbutleriii is correct that your proposal of adding the line ~/$MY_CONDA_INSTALLATION/etc/profile.d/conda.sh before calling "conda activate" now directly references your personal conda installation. That means that tools that generate "conda activate" calls (e.g. Nextflow) would have to be hand-patched for them to work correctly.

@stuarteberg proposed a perfectly reasonable solution that works (I tested it and yes it works), namely that conda init could add the following to your ~/.bashrc:

export -f conda
export -f __conda_activate
export -f __conda_reactivate
export -f __conda_hashr

I respectfully ask that you re-open this issue and use @stuarteberg's solution (or some other solution) fulfill the expected behavior requested by @mjspeck (i.e. "conda should activate in a bash script the same way it does on the command line"), because that behavior is (I believe) what conda's users are expecting. @stuarteberg's solution would be very easy to implement, and would indeed drastically reduce headaches.

Thank you!!

@leclairm
Copy link

@jasonsydes I fully agree.

I also had to add export -f __add_sys_prefix_to_path to my .bashrc in order to get rid of the __add_sys_prefix_to_path: command not found error.

Also note that, until this get fixed, you need to keep these export statements outside of the # >>> conda initialize >>> block so that it doesn't get removed in case you later run conda init bash

@stuarteberg
Copy link
Contributor

+1 for re-opening

@scopatz
Copy link
Contributor

scopatz commented May 15, 2019

I have noticed that you can do:

eval "$(conda shell.bash hook)"
conda activate <env-name>

@msarahan
Copy link
Contributor

Happy to reopen this, but we have no intention of doing development on this any time soon. The shell scripts are devilishly complicated, and we don't have time to get into them right now. What looks like a "simple change" may break a terrible number of seemingly unrelated stuff.

Community PRs are most welcome.

@f1am3d
Copy link

f1am3d commented Jul 29, 2019

@mjspeck

for Windows:

  1. Install Git Bash
  2. Open Git Bash
  3. type source ~/anaconda3/etc/profile.d/conda.sh
  4. type conda init
  5. Restart your shell
  6. Profit.

@Nilanshrajput
Copy link

@mjspeck

for Windows:

  1. Install Git Bash
  2. Open Git Bash
  3. type source ~/anaconda3/etc/profile.d/conda.sh
  4. type conda init
  5. Restart your shell
  6. Profit.

this works

@andrew-schweitzer-analog

This fixed the issue in my makefile: https://stackoverflow.com/a/55696820/4279266

@bryant1410
Copy link
Contributor

I think a cleaner way is:

eval "$(conda shell.bash hook)"
conda activate my_env

@SmadusankaB
Copy link

On the windows environment use "anaconda prompt" instead of "command prompt".

Go to search.
Type "anaconda prompt" and open it.
Then type "conda activate <env_name>

@omry
Copy link

omry commented Aug 25, 2019

Happy to reopen this, but we have no intention of doing development on this any time soon. The shell scripts are devilishly complicated, and we don't have time to get into them right now. What looks like a "simple change" may break a terrible number of seemingly unrelated stuff.

Community PRs are most welcome.

If you don't trust the project testing enough for doing delicate changes, how can you trust community PRs doing delicate changes?

@johann-petrak
Copy link

johann-petrak commented Apr 7, 2023

It is extremely annoying that there is no properly documented way of how to do this. Many people need this to automate jobs which require activating conda environments from within various kinds of scripts and the internet is full with contradicting and diverse recipes for how to do this, which work for some people and not for others.
There should be one proper recommended way for how to do this which is properly documented and supported.

@adrinjalali
Copy link

FWIW, in the meantime, there's micromamba with descent docker images and a much faster response rate, which many of us have migrated to: https://mamba.readthedocs.io/en/latest/user_guide/micromamba.html

@johann-petrak
Copy link

johann-petrak commented Apr 7, 2023

FWIW, in the meantime, there's micromamba with descent docker images and a much faster response rate, which many of us have migrated to: https://mamba.readthedocs.io/en/latest/user_guide/micromamba.html

I think the only relevant point here would be if mamba/micromamba has a documented and working way for how to activate environments from within a script? How does Mamba differ from Conda in this respect, if at all?

@adrinjalali
Copy link

@johann-petrak
Copy link

@adrinjalali please keep this issue on topic, this is about conda having no well-documented way to activate an environment from within a script. I have tried mamba and had problems which should not get discussed here and mamba also does not document wheter this is a way that is supposed to work.

The issue here is that there are different recipes floating around for how to do this with Conda, which work for some people and not for others or work for some conda versions only and not for others.

Conda should provide a documented standard way for how to activate an environment from within a bash script. Then, if that does not work, it clearly is a bug that can get reported and fixed.

@adrinjalali
Copy link

I very much agree with you on all things here @johann-petrak , but I'm not suggesting mamba, I'm just saying moving to micromamba (very different from mamba) has solved my issues. I agree it would be very nice to fix this issue for conda (and mamba, which also uses conda), but it doesn't hurt to have an alternative which doesn't use conda or mamba and yet lets folks do what they intend to do.

cc'ing @wolfv re: docs though.

@JohannesWiesner
Copy link

For me, neither of the proposed methods work. E.g. I can create a test environment (conda create -n test_activate python=3.9) , and then create a bash script activate_env.sh with one of the following options:

1.)

#!/bin/bash
CONDA_BASE=$(conda info --base)
source $CONDA_BASE/etc/profile.d/conda.sh
conda activate test_activate

2.)

#!/bin/bash
eval "$(conda shell.bash hook)"
conda activate test_activate

3.) I also tried out this solution and to run the script in an interactive shell:

#!/usr/bin/env bash -l
conda activate test_activate

I do not get any errors when running these options but still the environment goes not get activated. I am using conda 4.12.0 on Ubuntu 22.04

@madjxatw
Copy link

madjxatw commented Aug 1, 2023

@rbutleriii

Is there a conda variable that always returns your base path regardless of your current location?

Try this:

CONDA_BASE=$(conda info --base)

This is not going to be working because conda couldn't be found. If you run a bash script from a graphical application and it will have an non-interactive shell environment that doesn't source your .bashrc.

@h-vetinari
Copy link

h-vetinari commented Aug 1, 2023

Since this issue popped up again - I recently had to deal with this, and although I'm the first one to admit that it's a disgusting hack, at least it works (for my use-case). 😅

This is bash-only, not compatible with any other shell.

# we need to ensure our current process (in which this script is running) can
# find the activation mechanisms; usually these are inserted into ~/.bashrc,
# but in this shell, this isn't loaded.
# Extract the part that `conda init` has inserted (which conveniently has
# markers around it). Ensure sed-replacement can deal with multiline, see
# https://unix.stackexchange.com/a/152389
if [ ! -f .localinitrc ]; then
    extract=$(cat ~/.bashrc | tr '\n' '\f' | sed -E 's/.*\# >>> conda initialize >>>(.*)\# <<< conda initialize <<<.*/\1/g' | tr '\f' '\n')
    echo "$extract" > .localinitrc
fi
# run extracted bits in this process
source .localinitrc

@jmimi
Copy link

jmimi commented Aug 6, 2023

For me, neither of the proposed methods work. E.g. I can create a test environment (conda create -n test_activate python=3.9) , and then create a bash script activate_env.sh with one of the following options:

1.)

#!/bin/bash
CONDA_BASE=$(conda info --base)
source $CONDA_BASE/etc/profile.d/conda.sh
conda activate test_activate

2.)

#!/bin/bash
eval "$(conda shell.bash hook)"
conda activate test_activate

3.) I also tried out this solution and to run the script in an interactive shell:

#!/usr/bin/env bash -l
conda activate test_activate

I do not get any errors when running these options but still the environment goes not get activated. I am using conda 4.12.0 on Ubuntu 22.04

I had the same situation.
Please take a look at this solution

@JohannesWiesner
Copy link

JohannesWiesner commented Aug 7, 2023

I had the same situation. Please take a look at this solution

@jmimi : But this would only work for Linux right?

@jmimi
Copy link

jmimi commented Aug 7, 2023

I had the same situation. Please take a look at this solution

@jmimi : But this would only work for Linux right?

It should work for macos too. It is only shell script.

@JohannesWiesner
Copy link

I had the same situation. Please take a look at this solution

@jmimi : But this would only work for Linux right?

It should work for macos too. It is only shell script.

Sorry, phrased the question wrong: This won't work on Windows would be the better question.

@ChrisBarker-NOAA
Copy link

Windows is a whole different story. This issue is about a "bash script" -- bash is a *nix shell.

IIUC, conda support powershell, I'd look for solutions there. (Or the older cmd shell)

@jmimi
Copy link

jmimi commented Aug 7, 2023

I had the same situation. Please take a look at this solution

@jmimi : But this would only work for Linux right?

It should work for macos too. It is only shell script.

Sorry, phrased the question wrong: This won't work on Windows would be the better question.

For windows ChrisBarker said about that.
You mentioned using bash in your post implicitly so I thought your problem is with bash.

@tashrifbillah
Copy link

For future Googlers, I am writing out my problem and how #7980 (comment) helped solve it. I originally had

source ~/miniconda3/bin/activate
conda activate my_env

within a script to which $1 was passed. This approach reported 'harmless' (I think) errors:

Could not find conda environment: B10690
You can list all discoverable environments with conda info --envs.

I found the reason for the error within ~/miniconda3/bin/activate script:

...
...
\. "$_CONDA_ROOT/etc/profile.d/conda.sh" || return $?
conda activate "$@"

The last line attempted to source non-existence environment $1. I solved this by following #7980 (comment) : instead of the first block of code above, I put:

source ${NEW_SOFT_DIR}/miniconda3/etc/profile.d/conda.sh
conda activate my_env

Enjoy ...

@jlwwbo
Copy link

jlwwbo commented Aug 19, 2023

I have faced the same problem and found an unexpectedly simple solution.

Some Contexts: I use the shell script to setup a separate environment for each python project. These projects are located in the server (CentOS 7.9) so I connect to the workspace folder by ssh in vscode which is a bash terminal.

The solution is to use the source setup.sh rather than sh setup.sh to execute the given shell. No additional command is needed in the shell except the conda activate example_env command.

Hope it works!

@johann-petrak
Copy link

I have faced the same problem and found an unexpectedly simple solution.

That sadly is not a solution because the very problem discussed in this issue is to set the conda environment from within a bash script that is getting executed from a new bash command. There are many reasons why one may want to avoid sourcing commands and instead running a script from a new shell and there we face the problem.

Sadly the conda developers have not provided any documented standard solution for this and people are continuing to share anectodal evidence of what may or may not work in certain situations for some.
This is a really significant failure of the conda developers to address a problem that many many users face again and again and one can see that developers did not react to this issue in any constructive way since it was opened almost five years (!!) ago.

@jlwwbo
Copy link

jlwwbo commented Aug 21, 2023

I have faced the same problem and found an unexpectedly simple solution.

That sadly is not a solution because the very problem discussed in this issue is to set the conda environment from within a bash script that is getting executed from a new bash command. There are many reasons why one may want to avoid sourcing commands and instead running a script from a new shell and there we face the problem.

Sadly the conda developers have not provided any documented standard solution for this and people are continuing to share anectodal evidence of what may or may not work in certain situations for some. This is a really significant failure of the conda developers to address a problem that many many users face again and again and one can see that developers did not react to this issue in any constructive way since it was opened almost five years (!!) ago.

OK I get it. btw, why should not soucing command for a bash script? Maybe for the security issue?

@jacobwilliams
Copy link

jacobwilliams commented Sep 9, 2023

+1 that this is a serious problem. It's always a chore to figure out which of these hacks is going to make it work on any given system I have to deal with.

@Lolzen
Copy link

Lolzen commented Nov 9, 2023

Nothing here semmed to work, but i read somewhere it's supposed to be an interactive shell command, so my research towards that got me here.

so in the end this command did finally work (obv replace $conda_env with your env name)
bash --init-file <(echo ". "$HOME/.bashrc"; conda activate $conda_env")

@AmineDjeghri
Copy link

I have noticed that you can do:

eval "$(conda shell.bash hook)"
conda activate <env-name>

perfect !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backlog issue has been triaged but has not been earmarked for any upcoming release cli pertains to the CLI interface good first issue great for new contributors, code change is envisioned to be trivial/relatively straight-forward severity::3 major; broken functionality with a workaround source::community catch-all for issues filed by community members type::bug describes erroneous operation, use severity::* to classify the type
Projects
Status: No status
Development

No branches or pull requests