#!/usr/bin/env bash ############# # Variables # ############# # Define formatting variables fb="$(tput bold)" fr="$(tput sgr0)" # Set virtual environments directory ves_dir="" # Set projects directory projs_dir="" # Create required variables array required_vars=( 'projs_dir' 'ves_dir' ) ############# # Functions # ############# display_usage() { local help_msg help_msg="Usage: . '${0}' Purpose: Activate a Python virtual environment. Variables to set: projs_dir Directory of projects. ves_dir Virtual environments directory." echo "${help_msg}" } # Parse arguments parse_args() { local parsed_args inv_ents parsed_args="$(getopt \ -n "${0##*/}" \ -o h \ --long help \ -- "${@}")" # Check for invalid entries inv_ents="${?}" ; readonly inv_ents if [[ "${inv_ents}" -ne 0 ]]; then echo '' display_usage exit 1 fi # Set positional parameters using parsed argument string eval set -- "${parsed_args}" # Evaluate options while true; do case "${1}" in '-h' | '--help') display_usage exit 0 ;; '--') ## End of options shift break ;; esac done } # Run initialization checks run_init_cks() { # Verify script was loaded via . command if ! [[ "${BASH_SOURCE[0]}" != "${0}" ]]; then echo -e "\nRerun script using the ${fb}.${fr} command." 1>&2 && exit 1 fi } # Display virtual environment menu ve_menu() { PS3='Select a virtual environment: ' select ve in "${ves[@]}"; do if ! [[ "${ve}" ]]; then echo -e '\nPlease enter a valid menu selection.\n' 1>&2 ve_menu break elif [[ "${ve}" == 'Quit' ]]; then break else . "${ves_dir}/${ve}/bin/activate" break fi done } # Display projects menu proj_menu() { PS3='Select a project: ' select proj in "${projs[@]}"; do if ! [[ "${proj}" ]]; then echo -e '\nPlease enter a valid menu selection.\n' 1>&2 proj_menu break elif [[ "${proj}" == 'Quit' ]]; then break else cd "${projs_dir}/${proj}" || exit 1 break fi done } # Define starting point for execution of the program main() { parse_args "${@}" run_init_cks # Create unset variables array declare -a unset_vars # Verify that required variables are set for required_var in "${required_vars[@]}"; do if ! [[ "${!required_var}" ]]; then unset_vars+=("${required_var}") fi done # Display error message if variables are not set if [[ "${unset_vars[*]}" ]]; then err_msg='\nSet the following variable(s) before ' err_msg+='running the script again:' echo -e "${err_msg}\n${fb}${unset_vars[*]}${fr}" 1>&2 else # Declare virtual environments indexed array declare -a ves # Define virtual environments array mapfile -t ves < \ <(find "${ves_dir}" -mindepth 1 -maxdepth 1 -type d -printf '%f\n') ves+=('Quit') # Add quit option to ves array ve_menu # Display virtual environment menu if ! [[ "${ve}" == 'Quit' ]]; then declare -a projs mapfile -t projs < \ <(find "${projs_dir}" -mindepth 1 -maxdepth 1 -type d -printf '%f\n') projs+=('Quit') echo '' proj_menu # Display projects menu fi fi } ########### # Program # ########### main "${@}" # Start program