#!/bin/bash
unset option menu ERROR # prevent inheriting values from the shell
declare -a menu # create an array called $menu
menu[0]="" # set and ignore index zero so we can count from 1
# read menu file line-by-line, save as $line
while IFS= read -r line; do
menu[${#menu[@]}]="$line" # push $line onto $menu[]
done < ingestion.txt
# function to show the menu
menu() {
echo "Please select an option by typing in the corresponding number"
echo ""
for (( i=1; i<${#menu[@]}; i++ )); do
echo "$i) ${menu[$i]}"
done
echo ""
}
# initial menu
menu
read option
# loop until given a number with an associated menu item
while ! [ "$option" -gt 0 ] 2>/dev/null || [ -z "${menu[$option]}" ]; do
echo "No such option '$option'" >&2 # output this to standard error
menu
read option
done
echo "You said '$option' which is '${menu[$option]}'"
This reads through ingestion.txt line by line, then pushes the contents of that line into the $menu
array. ${#variable}
gives you the length of $variable
. When given the entirety of an array ("${array[@]}"
is akin to "$@"
), such as ${#array[@]}
, you get the number of elements in that array. Because bash is zero-indexed, that number is the first available item you can add to, starting with zero given the newly defined (and therefore empty) array.
The menu()
function iterates through the menu items and displays them on the screen.
We then loop until we get a valid input. Since bash will interpret a non-number as zero, we first determine if it is actually a (natural) number, discarding any error that would come from non-numbers, then we actually ensure the index exists. If it's not the first iteration, we complain about the invalid input given before. Display the menu, then read
user input into $option
.
Upon a valid option index, the loop stops and the code then gives you back the index and its corresponding value.