Skip to content

Instantly share code, notes, and snippets.

@itxx00
Created May 22, 2020 08:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itxx00/a3b5756e0368f9c3ac24ead22bbf4a12 to your computer and use it in GitHub Desktop.
Save itxx00/a3b5756e0368f9c3ac24ead22bbf4a12 to your computer and use it in GitHub Desktop.
#!/bin/bash
menu_select() {
declare -a menu
local options="$@"
menu=($options)
cur=0
draw_menu() {
for i in "${menu[@]}"; do
if [[ ${menu[$cur]} == $i ]]; then
tput setaf 2; echo " > $i"; tput sgr0
else
echo " $i";
fi
done
}
clear_menu() {
for i in "${menu[@]}"; do tput cuu1; done
tput ed
}
# Draw initial Menu
draw_menu
while read -sN1 key; do # 1 char (not delimiter), silent
# Check for enter/space
if [[ "$key" == "" ]]; then break; fi
# catch multi-char special key sequences
read -sN1 -t 0.0001 k1; read -sN1 -t 0.0001 k2; read -sN1 -t 0.0001 k3
key+=${k1}${k2}${k3}
case "$key" in
# cursor up, left: previous item
h|k|$'\e[A'|$'\e0A'|$'\e[D'|$'\e0D') ((cur > 0)) && ((cur--));;
# cursor down, right: next item
j|l|$'\e[B'|$'\e0B'|$'\e[C'|$'\e0C') ((cur < ${#menu[@]}-1)) && ((cur++));;
# home: first item
$'\e[1~'|$'\e0H'|$'\e[H') cur=0;;
# end: last item
$'\e[4~'|$'\e0F'|$'\e[F') ((cur=${#menu[@]}-1));;
# q, carriage return: quit
q|''|$'\e')echo "Aborted." && exit;;
esac
# Redraw menu
clear_menu
draw_menu
done
echo "Selected item $cur: ${menu[$cur]}";
}
menu_select aa bb cc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment