Last active
July 1, 2023 13:31
-
-
Save mwakok/a89eaa93b3a0e2d85b6702e22fe237b3 to your computer and use it in GitHub Desktop.
Activate conda environment with cd in bash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Adapted from: https://janosh.dev/blog/conda-auto-env | |
# | |
# Automatically activates conda environments when entering directories | |
# containing a conda environment file. The file must be named | |
# - env(ironment).y(a)ml | |
# Deactivates env when exiting the directory. If the env doesn't exist yet, | |
# offer to create it from file. The script will use mamba if available. | |
# | |
# Setup: | |
# Option 1) Add the code below to .bashrc | |
# Option 2) Save the code in a separate file ('.conda_auto_env.sh') and add 'source <path-to-file>/.conda_auto_env.sh' to .bashrc or .bash_profile | |
_activate_conda() { | |
FILE="$(find . -maxdepth 1 -regextype posix-extended -regex '.*env(ironment)?\.ya?ml' -print -quit)" | |
if [[ -e $FILE ]]; then | |
ENV=$(sed -n 's/name: //p' $FILE) | |
# Check if env is already active. | |
if [[ $CONDA_DEFAULT_ENV != $ENV ]]; then | |
conda activate $ENV | |
# If env activation is unsuccessful, prompt user whether to create conda env from file. | |
if [ $? -ne 0 ]; then | |
while true; do | |
# Read user reply into variable choice. | |
read -p "Environment '$ENV' doesn't exist. Would you like to create it now? (y/[n]) " yn | |
if [ "$yn" = "" ]; then yn='n'; fi # interpret Enter as n | |
case $yn in | |
[Yy] ) echo Proceeding...; | |
mamba env create -f $FILE || conda env create -f $FILE; | |
echo "Activating environment '$ENV'..." | |
conda activate $ENV; | |
break;; | |
[Nn] ) echo Exiting...; | |
break;; | |
* ) echo "Invalid response";; | |
esac | |
done | |
fi | |
CONDA_ENV_ROOT="$(pwd)" | |
fi | |
# Deactivate env when exiting the env file's directory. | |
elif [[ $PATH = */envs/* ]]\ | |
&& [[ $(pwd) != $CONDA_ENV_ROOT ]]\ | |
&& [[ $(pwd) != $CONDA_ENV_ROOT/* ]] | |
then | |
CONDA_ENV_ROOT="" | |
conda deactivate | |
fi | |
} | |
# Update the existing cd function to chain it with _activate_conda | |
function cd { | |
builtin cd "$@" ; _activate_conda | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment