Home > Software engineering >  Bash script if else not working as expected for arrays
Bash script if else not working as expected for arrays

Time:07-29

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?

CodePudding user response:

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
  • Related