Skip to content

Instantly share code, notes, and snippets.

@gitmpr
Last active June 18, 2024 17:01
Show Gist options
  • Save gitmpr/34c452a422cacbc92c8b6bedbc151985 to your computer and use it in GitHub Desktop.
Save gitmpr/34c452a422cacbc92c8b6bedbc151985 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# Define the menu menu_options
menu_options=("Option 0" "Option 1" "Option 2" "Option 3" "Option 4" "option 5")
num_menu_options=${#menu_options[@]}
# enable/disable looping of the selection
looping=0
# Initialize the selected option index
selected=0
# Function to print the menu
print_menu() {
#clear
for i in "${!menu_options[@]}"; do
if [ $i -eq $selected ]; then
echo -e "\e[7m> ${menu_options[$i]}\e[m"
else
echo " ${menu_options[$i]}"
fi
done
}
# Move the cursor back up
reset_cursor() {
echo -en "\e["$num_menu_options"A"
}
# Function to handle keypress events
keypress() {
local key
read -rsn1 key
case "$key" in
"A"|"k") # Up arrow
((selected--))
if [ $selected -lt 0 ]; then
# selected=$((${#menu_options[@]} - 1))
#selected=0
if [ "$looping" -eq 1 ]; then
selected=$((${#menu_options[@]} - 1))
else
selected=0
fi
fi
;;
"B"|"j") # Down arrow
((selected++))
if [ $selected -ge ${#menu_options[@]} ]; then
#selected=0
#selected=$((${#menu_options[@]} - 1))
if [ "$looping" -eq 1 ]; then
selected=0
else
selected=$((${#menu_options[@]} - 1))
fi
fi
;;
"") # Enter key
# clear
echo "Selected: $selected"
echo "Selected: ${menu_options[$selected]}"
exit 0
;;
esac
}
showcursor() {
echo -en "\033[?25h"
}
hidecursor() {
echo -en "\033[?25l"
}
# Trap the EXIT signal to ensure cursor is restored before exiting
trap showcursor EXIT
hidecursor
print_menu
while true; do
reset_cursor
print_menu
keypress
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment