Created
November 27, 2020 21:52
-
-
Save lordlycastle/e5e19979977bd642bb33da0d73b9cc04 to your computer and use it in GitHub Desktop.
Bash script to prompt user to choose from list of options. (Bash makes everything so hard.)
This file contains hidden or 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/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