I'm working on a custom bash script (with which I have very little experience) and I'm looking for some help with a menu function. My script had several different menus accomplishing different functions so I decided to create one menu function that could be called and customized with set variables. It's unclean and ugly, but I've learned a lot making it. Can anyone shed some light on where I could have simplified or done things differently or more cleanly? Thanks in advance!
#!/bin/bash
# set colors
red='tput setaf 1'
blue='tput setaf 4'
green='tput setaf 2'
bold='tput bold'
normal='tput sgr0'
# define function to reset screen to title
function reset {
clear
$bold
$blue
echo -e "lineage build script\n\n"
$normal
}
function title {
reset
$bold
echo -e "$1\n"
$normal
}
# function to create menu
# menu "<title(required)>" "<question(required)>" <all(required)> "<option1>"...
# <title> - Page title
# <question> - Question to be posed before the menu
# <all> - Whether or not to present a menu choice for "All"
# <option#> - List of options to present to the user
function menu {
# set input at 255 (max error level for return function later)
input=255
# check input to see if it's acceptable (within presented range and a number)
while [[ $input -ge $(($counter+1)) ]] || [[ $((input)) != $input ]]; do
# a call to a previously defind function establishing consistent page feel.
title "$1"
echo -e "$2"
# present warning if input was invalid
if ! [[ $input =~ "255" ]]; then
$red
echo -e "Invalid entry. Please try again.\n"
$normal
else
echo -e "\n"
fi
counter=0
# present list items for each variable passed to function starting at position 4
# in order to skip the first 3 (title, question, all)
for i in "${@:4}"; do
counter=$(($counter+1))
echo -e "$counter) $i"
done
# present "All" option if variable 3 is any form of yes
if [[ $3 =~ (y|yes|Y|YES) ]]; then $green; counter=$(($counter+1)); echo -e "$counter) All"; $normal; fi
# present "Exit" option
$red; counter=$(($counter+1)); echo -e "$counter) Exit\n"; $normal
# gather input
read -N 1 -p "[1-$counter]: " input
done
# bail if exit was chosen
if [[ $input == $counter ]]; then $red; echo -e "\nExit"; exit; fi
# pass choice back to script as return code
return $input
}
# call the menu function for testing
menu "Main Menu" "What would you like to do?" y "option 1" "option 2" "option 3" "option 4" "option 5"
#echo return code just to verify function
echo -e "\nYou chose $?"