-1

Running the command eval "conda env list | cut -d ' ' -f 1" on the terminal gets me the following output enter image description here

I want to check if a conda virtual environment already exits using a bash script. Here is my code

#!/bin/bash
mapfile -t env_array < <(eval "conda env list | cut -d ' ' -f 1")
env_name="ihop3"
echo $env_name;
echo "${env_array[@]}";
if [[ ${env_array[$env_name]} ]]; then
    echo 'Venv exists. Activating ihop environment';
else
    echo 'Venv does not exist. Creating ihop environment';
fi

As you can see, I am checking for an environment named "ihop3", which should return False. But executing the above bash script does not work. Also notice that the array shows the environment names as expected. Here is the output enter image description here

Can anyone suggest a solution?

Shrayani Mondal
  • 160
  • 1
  • 7
  • Why are you using `eval`? This is only needed if you're creating the command dynamically. – Barmar Jul 27 '22 at 23:13
  • 1
    `env_array` is not an associative array. Why are you trying to use `ihop3` as an index? – Barmar Jul 27 '22 at 23:14
  • 1
    Please post code, data, and results as text, not screenshots. http://idownvotedbecau.se/imageofcode – Barmar Jul 27 '22 at 23:15
  • 1
    `${env_array[$env_name]}` does not do what you seem to think it does. It doesn't search the array for an element matching `$env_name`, it fetches element number `$env_name`... which isn't a number, so bash does its best to convert it to a number and winds up with 0. So `${env_array[$env_name]}` -> `${env_array[ihop3]}` -> `${env_array[0]}` -> `ihop`. – Gordon Davisson Jul 28 '22 at 01:11

1 Answers1

0

You can use grep to test if the output of conda env list contains the name you're looking for.

env_name="ihop3"
if conda env list | grep -q "^$env_name "
then echo 'Venv exists. Activating ihop environment'
else echo 'Venv does not exist. Creating ihop environment'
fi
Barmar
  • 741,623
  • 53
  • 500
  • 612