Guest User

Untitled

a guest
May 17th, 2021
112
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #  Arguments:
  2. #    index of preselected option
  3. #    array of options
  4. #
  5. #  Return value:
  6. #    selected index (0 for opt1, 1 for opt2 ...)
  7. #
  8. function select_option {
  9.     start_idx=$1
  10.     shift
  11.     options=("$@")
  12.  
  13.     # helpers for terminal print control and key input
  14.     ESC=$(printf "\033")
  15.     cursor_blink_on()   { printf "$ESC[?25h"; }
  16.     cursor_blink_off()  { printf "$ESC[?25l"; }
  17.     cursor_to()         { printf "$ESC[$1;${2:-1}H"; }
  18.     print_option()      { printf "   $1 "; }
  19.     print_selected()    { printf "${COLOR_GREEN}  $ESC[7m $1 $ESC[27m${NC}"; }
  20.     get_cursor_row()    { IFS=';' read -sdR -p $'\E[6n' ROW COL; echo ${ROW#*[}; }
  21.     key_input()         { read -s -n3 key 2>/dev/null >&2
  22.                          if [[ $key = $ESC[A ]]; then echo up; fi
  23.                          if [[ $key = $ESC[B ]]; then echo down; fi
  24.                          if [[ $key = ""     ]]; then echo enter; fi; }
  25.  
  26.     # initially print empty new lines (scroll down if at bottom of screen)
  27.     for opt in "${options[@]}"; do printf "\n"; done
  28.  
  29.     # determine current screen position for overwriting the options
  30.     local lastrow=`get_cursor_row`
  31.     local startrow=$(($lastrow - $#))
  32.  
  33.     # ensure cursor and input echoing back on upon a ctrl+c during read -s
  34.     trap "cursor_blink_on; stty echo; printf '\n'; exit" 2
  35.     cursor_blink_off
  36.  
  37.     local selected=$start_idx
  38.     while true; do
  39.         # print options by overwriting the last lines
  40.         local idx=0
  41.         for opt in "${options[@]}"; do
  42.             cursor_to $(($startrow + $idx))
  43.             if [ $idx -eq $selected ]; then
  44.                 print_selected "$opt"
  45.             else
  46.                 print_option "$opt"
  47.             fi
  48.             ((idx++))
  49.         done
  50.  
  51.         # user key control
  52.         case `key_input` in
  53.             enter) break;;
  54.             up) ((selected--));
  55.                     if [ $selected -lt 0 ]; then selected=$(($# - 1)); fi;;
  56.             down)  ((selected++));
  57.                     if [ $selected -ge $# ]; then selected=0; fi;;
  58.         esac
  59.     done
  60.  
  61.     # cursor position back to normal
  62.     cursor_to $lastrow
  63.     cursor_blink_on
  64.     echo
  65.  
  66.     return $selected
  67. }
  68.  
  69.  
  70. # Usage:
  71. deployment_targets=('staging' 'production')
  72. default_target_idx=0
  73.  
  74. select_option $default_target_idx "${deployment_targets[@]}"
  75.  
RAW Paste Data