DEV Community

William Lake
William Lake

Posted on

Bash Functions for Miniconda

Qualifier: These instructions were made with Ubuntu 18.04 in mind. Your mileage may vary.

A little under 2 years ago a friend introduced me to miniconda and I've loved it ever since. I know there's other ways manage python virtual environments (I use pipenv at work and there's always venv,) but I've stuck with miniconda in my personal projects out of habit. If you use miniconda on Ubuntu, hopefully you'll find this helpful.

Short & Sweet

Add the following functions to your ~/.bashrc file. Don't forget to reload your .bashrc before using them! (Reload via source .bashrc)

newconda

Creates a new python conda environment and installs the listed modules.

NOTE: This function doesn't ask for confirmation! This is personal preference, but if you'd like to change it remove the y in -yn (E.g. conda create -n "$1" python="$2"

# Creates a new python conda environment and installs the listed modules.
# $1 : Environment Name (E.g. test_env)
# $2 : Python Version (E.g. 3)
# $3...$n+1 : A list of modules to install.
# 
# E.g.
#       newconda test_env 3 numpy pandas
#       newconda test_env 3.6 tensorflow tensorflow-hub tensorflow-datasets
newconda() {

        # Create the env with the given name and python version.
        # Note: -y forces yes, you won't be asked for confirmation.
        conda create -yn "$1" python="$2"

        # Activate the environment.
        conda activate "$1"

        # Loop through the remaining arguments, installing them as python modules.
        for i in "${@:3}"
                do pip install "$i"
        done
}

Enter fullscreen mode Exit fullscreen mode

remconda

Removes the listed conda environment.

NOTE: This function doesn't ask for confirmation! This is personal preference, but if you'd like to change it remove the y in -yn (E.g. conda env remove -n "$1")

# Removes the listed conda environment.
# $1 : The name of the environment to remove.
#
# E.g. 
#       remconda test_env
remconda() {
        # Deactivate the current environment.
        # (In case you're in the target environment.)
        conda deactivate

        # Remove the environment.
        # Note: -y forces yes, you won't be asked for confirmation.
        conda env remove -yn "$1"
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)