Conda command working in command prompt but not in bash script

my anaconda (4.5.4) works fine as long as I just use it via a linux terminal (bash shell). However, running conda commands in a bash script does not work at all.

The script test.sh containes these lines:

#!/bin/bash
conda --version
conda activate env

Now, running bash test.sh results in the error

test.sh: line 2: conda: command not found
test.sh: line 3: conda: command not found

As recommended for anaconda version > 4.4 my .bashrc does not contain

export PATH="/opt/anaconda/bin:$PATH",

but

. /opt/anaconda/etc/profile.d/conda.sh

Thank you.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

I solved the problem thanks to @darthbith ‘s comment.

Since conda is a bash function and bash functions can not be propagated to independent shells (e.g. opened by executing a bash script), one has to add the line

source /opt/anaconda/etc/profile.d/conda.sh

to the bash script before calling conda commands. Otherwise bash will not know about conda.

Solution 2

If @randomwalker’s method doesn’t work for you, which it won’t any time your script is run in a more basic shell such as sh, then you have two options.

  1. Add this to your script: eval $(conda shell.bash hook)

  2. Call your script with: bash -i <scriptname> so that it runs in your interactive environment.

Solution 3

Let’s say you try to access user name with "miky" @ "server" address.First when you login to your user ; learn conda path with "which conda" then probably you will get a path such as "/home/miky/anaconda3/bin/conda"
then put your conda commands as follow (in my example i use conda to install a mysql plugin forexample.): shh [email protected] -t "/home/miky/anaconda3/bin/conda install -y -c anaconda mysql-connector-python" thats all.

Solution 4

do sudo ln -s /home/<user>/miniconda3/etc/profile.d/conda.sh /etc/profile.d/conda.sh and try again. This should activate conda for all users permenantly

source

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply