Skip to content

Instantly share code, notes, and snippets.

@1cadumagalhaes
Created May 26, 2023 18:18
Show Gist options
  • Save 1cadumagalhaes/beface90e882be4dc140d169228346db to your computer and use it in GitHub Desktop.
Save 1cadumagalhaes/beface90e882be4dc140d169228346db to your computer and use it in GitHub Desktop.
Shell script developed to center python virtual environment commands. To use, just place it on /usr/loca/bin/pyenvs and you can run as: pyenvs list, pyenvs create [environment], source pyenvs activate [environment]
#!/bin/zsh
function create_venv() {
if [ $# -eq 0 ]; then
echo "Please provide the name of the virtual environment to create"
return 1
fi
venv_name="$1"
venv_dir="$HOME/.venvs"
if [ $# -eq 2 ]; then
venv_dir="$2"
fi
python3 -m venv "$venv_dir/$venv_name"
}
# Function to activate a virtual environment
function activate_venv() {
# echo "Activating venv: $1"
if [ $# -eq 0 ]; then
echo "Please provide the name of the virtual environment to activate"
return 1
fi
venv_name="$1"
venv_dir="$HOME/.venvs"
if [ $# -eq 2 ]; then
venv_dir="$2"
fi
activate_dir="$venv_dir/$venv_name"
if [ ! -d "$activate_dir" ]; then
echo "Error: virtual environment '$venv_name' does not exist"
return 1
fi
source "$activate_dir/bin/activate"
echo "$activate_dir/bin/activate"
}
# Function to list all virtual environments
function list_venv() {
echo "Available virtual environments:"
for venv_dir in "$HOME"/.venvs/*/; do
if [ -d "$venv_dir" ]; then
venv_name=$(basename "$venv_dir")
echo "- $venv_name"
fi
done
}
# Function to delete a virtual environment
function delete_venv() {
if [ $# -eq 0 ]; then
echo "Please provide the name of the virtual environment to delete"
return 1
fi
venv_name="$1"
venv_dir="$HOME/.venvs"
if [ $# -eq 2 ]; then
venv_dir="$2"
fi
venv_dir="$venv_dir/$venv_name"
if [ ! -d "$venv_dir" ]; then
echo "Error: virtual environment '$venv_name' does not exist"
return 1
fi
# Prompt the user for confirmation
echo "Are you sure you want to delete the virtual environment '$venv_name'? [y/n]"
read confirmation
if [ "$confirmation" != "y" ]; then
echo "Deletion of virtual environment '$venv_name' cancelled"
return 1
fi
# Delete the virtual environment
rm -rf "$venv_dir"
echo "Virtual environment '$venv_name' deleted"
}
# Check command line arguments
case $1 in
create)
shift
create_venv "$@"
;;
activate)
shift
activate_venv "$@"
;;
list)
list_venv
;;
delete)
shift
delete_venv "$@"
;;
*)
echo "Usage: $0 {create <venv_name> [<dir>]|activate <venv_name>|list|delete <venv_name> [<dir>]}"
exit 1
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment