Skip to content

Instantly share code, notes, and snippets.

@trevor-coleman
Last active May 4, 2023 15:56
Show Gist options
  • Save trevor-coleman/9c753b69c9871daf293812fd8f5eb473 to your computer and use it in GitHub Desktop.
Save trevor-coleman/9c753b69c9871daf293812fd8f5eb473 to your computer and use it in GitHub Desktop.
Command Chooser
#!/bin/bash
# This script reads a list of descriptions and commands from a YAML-like input file and presents the options to the user.
# Each option has a description and an associated command.
# The input file format should be as follows:
#
# - description: "Description 1"
# command: "command1"
# - description: "Description 2"
# command: "command2"
#
# Usage: ./command-menu.sh <commands_file>
# Replace <commands_file> with the name of your input file containing the descriptions and commands.
#
# Note: Remember to make the script executable with `chmod +x command-menu.sh`
# Define ANSI escape codes for colors
RED='\033[0;31m'
BLUE='\033[0;34m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color
if [ "$#" -ne 1 ]; then
echo "Usage: $0 <commands_file>"
exit 1
fi
# Read the file and store the descriptions and commands in arrays
filename="$1"
descriptions=()
commands=()
while IFS= read -r line
do
if [[ "$line" =~ ^"- description: \"(.*)\"" ]]; then
description="${BASH_REMATCH[1]}"
descriptions+=("$description")
elif [[ "$line" =~ ^" command: \"(.*)\"" ]]; then
command="${BASH_REMATCH[1]}"
commands+=("$command")
fi
done < "$filename"
# Print the list of options with a leading number
printf "${BLUE}"
echo "Please choose an option:"
echo
printf "${NC}"
for i in "${!descriptions[@]}"; do
printf "${YELLOW}$(($i+1)))${NC} ${descriptions[$i]}\n"
done
echo
# Prompt the user to select one of the options
read -p "Enter the number of the desired option: " choice
# Validate user input and run the associated command
if [[ $choice -ge 1 && $choice -le ${#descriptions[@]} ]]; then
printf "\n\n${RED} Running command: ${descriptions[$(($choice-1))]}${NC}\n\n"
eval "${commands[$(($choice-1))]}"
else
echo "Invalid option. Exiting."
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment