Skip to content

Instantly share code, notes, and snippets.

@henryefranks
Last active August 31, 2017 18:05
Show Gist options
  • Save henryefranks/a391f2a808674646d47b990534226916 to your computer and use it in GitHub Desktop.
Save henryefranks/a391f2a808674646d47b990534226916 to your computer and use it in GitHub Desktop.
A Bash script for an interactive CLI select menu without curses
#!/usr/local/bin/bash
stty -echo
tput civis
function cleanup() {
stty echo
tput cnorm
}
function interrupt() {
cleanup
exit
}
trap interrupt INT
if [ "$#" -le "1" ]; then
echo "Error: Not enough options"
kill -INT $$ # To stop exiting when run as source script
fi
selected=0
function echo_menu() {
# Echo the menu with the selected option highlighted
count=0
tput sgr0
echo -n " " # Indent
for opt in "$@"; do
if [ "$count" -eq "$selected" ]; then
tput rev
else
tput sgr0
fi
echo -n "$opt"
count=$(($count + 1))
tput sgr0
echo -n " " # Padding
done
echo
}
echo_menu "$@"
while read -rsn1 key; do
case "$key" in
$'\x1b')
read -rsn1 -t 0.1 key
if [ "$key" == "[" ]; then
read -rsn1 -t 0.1 key
case "$key" in
"A" | "D")
if [ "$selected" -gt "0" ]; then
selected=$(($selected - 1))
fi
tput cuu1
echo_menu "$@"
;;
"B" | "C")
if [ "$selected" -lt "$(($# - 1))" ]; then
selected=$(($selected + 1))
fi
tput cuu1
echo_menu "$@"
;;
esac
fi
;;
"" | "\n")
selected_adjust=$(($selected + 1))
export answer=${!selected_adjust} # Return value from function (only works when script is sourced)
break
;;
esac
done
cleanup
# +------------------------------------+
# | Example usage (in another script): |
# +------------------------------------+
#
# #!/bin/bash
# echo 'exit?'
# . ./options.sh Yes No # NOTE: the preceding dot is necessary to make the answer accessible
# if [ "$answer" == "Yes" ]; then
# exit
# fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment