Last active
February 28, 2024 07:44
-
-
Save metalelf0/b471f943dcad69d99548243bd2973faf to your computer and use it in GitHub Desktop.
Sample zsh script with both interactive user menu and direct input
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env zsh | |
# Call this script with: | |
# ./eat-food.zsh [opt] | |
# | |
# If a food is given, and is in the valid foods (opts array), it will eat the given food | |
# e.g. ./eat-food.zsh bananas | |
# | |
# If a food is given, but it's not valid, it will prompt for a food to eat | |
# e.g. ./eat-food.zsh pineapples | |
# | |
# If no food is given, it will show the food menu | |
# e.g. ./eat-food.zsh | |
declare -A opts | |
opts=( [1]=apples [2]=potatoes [3]=bananas [q]=quit ) | |
function eat_food() { | |
food_name="$1" | |
echo "I am eating $food_name!" | |
} | |
function opts_has_value() { | |
for value in ${(v)opts}; do | |
if [ "$value" = "$1" ]; then | |
return 0 | |
fi | |
done | |
return 1 | |
} | |
function opts_has_key() { | |
for key in ${(k)opts}; do | |
if [ "$key" = "$1" ]; then | |
return 0 | |
fi | |
done | |
return 1 | |
} | |
function print_menu() { | |
echo "== Make your selection:" | |
for key in ${(kon)opts}; do | |
echo "$key -> $opts[$key]" | |
done | |
} | |
function read_from_menu() { | |
while true; do | |
print_menu | |
while true; do | |
echo -n "> " | |
read selection | |
echo | |
if ! opts_has_key $selection | |
then | |
echo "[ERROR] Invalid option: $selection" | |
echo | |
break | |
elif [ $selection = "q" ] | |
then | |
echo "Ok, bye!" | |
exit 0 | |
else | |
food_name=$opts[$selection] | |
eat_food "$food_name" | |
exit 0 | |
fi | |
done | |
done | |
} | |
if [ $1 ] && opts_has_value $1 | |
then | |
eat_food "$1" | |
else | |
read_from_menu | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment