calling conda source activate from bash script

I'm trying to activate my conda env via a bash script. Even though the script runs fine and my PATH appears to be changed within the script, it's getting reset somehow after the script terminates. I can call source activate test from the cmd line and it works fine. An example along with output below.

script:

PycharmProjects/test » cat ./example.sh
echo "before calling source: $PATH"
source activate test
echo "after calling source: $PATH"

output:

./example.sh
before calling source: /Use rs/me/miniconda3/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/TeX/texbin

discarding /Users/me/miniconda3/bin from PATH
prepending /Users/me/miniconda3/envs/test/bin to PATH

after calling source: /Users/me/miniconda3/envs/test/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/TeX/texbin`

but if I echo $PATH after the script finishes, you can see that the $PATH has not changed (i.e. no /Users/me/miniconda3/envs/test/bin):

PycharmProjects/test » echo $PATH /Users/me/miniconda3/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/TeX/texbin


Solution 1:

On more recent versions of conda (4.6+), I have noticed that the following works:

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

Solution 2:

I have found the following to work on Mac OSX running a bash shell:

#!/bin/bash
source /Users/yourname/anaconda/bin/activate your_env
python --version # example way to see that your virtual env loaded as expected

Make sure you make the scripted executable with:

chmod +x yourscript.bash

Solution 3:

See the link below,

digitalocean-how-to-read-and-set-environmental-and-shell-variables-on-a-linux-vps

below is the snippet from the website,

This is because environmental variables are only passed to child processes. There isn't a built-in way of setting environmental variables of the parent shell. This is good in most cases and prevents programs from affecting the operating environment from which they were called.