Advertisement
MestreLion

select replacement - for fun

Aug 6th, 2011
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.95 KB | None | 0 0
  1. #!/bin/bash
  2. #
  3. # A replacement for bash's "select" builtin command
  4. # (exercise only - not meant to be taken too seriously)
  5. #
  6. # Copyright (C) 2011 Rodrigo Silva (MestreLion) <[email protected]>
  7. # License: GPL v3 or later, at your choice. See <http://www.gnu.org/licenses/>
  8. #
  9.  
  10.  
  11. PS3="Choose an option (0 to quit): " # custom prompt (or comment for default)
  12.  
  13.  
  14. # ----- PARAMETERS ---------------------------------------------------------
  15.  
  16. # From help select:
  17. # select: select NAME [in WORDS ... ;] do COMMANDS; done
  18. #    Select words from a list and execute commands.
  19.  
  20. unset WORDS NAME
  21. declare -a WORDS=("AAA" "BBB" "CCC") # place options inside (...), blank for "$@"
  22. declare    NAME="option"             # name your output var
  23.  
  24.  
  25. # ----- SELECT/IN/DO STATEMENT - DO NOT EDIT --------------------------------
  26.  
  27. menu() {
  28.     for i in ${!WORDS[@]}; do
  29.         printf "%*d) %s\n" $(((${#WORDS[@]}/10)+1)) $((i+1)) "${WORDS[i]}"
  30.     done;
  31. }
  32. (( ${#WORDS[@]} )) || WORDS=("$@")
  33. while menu && read -rp "$PS3" REPLY && NUMREPLY=""; do
  34.     [[ "$REPLY" != *[![:digit:]]* ]] && NUMREPLY=$((10#$REPLY)) # avoid 08 error
  35.     (( NUMREPLY )) && declare "$NAME"="${WORDS[NUMREPLY-1]}" || declare "$NAME"=""
  36.  
  37.    
  38. # ---- INSIDE THE LOOP - EDITABLE -------------------------------------------
  39.  
  40. # Run your COMMANDS
  41.  
  42. # Do whatever you want, but of course, dont mess with WORDS, NAME or NUMREPLY
  43. # (remember those those are "inner" vars). But messing with REPLY
  44. # or with your named variable is allowed
  45.    
  46.     [[ ! "$REPLY" = "0" ]] || { echo "Goodbye!" ; break; }
  47.     echo "You picked $option which is option $REPLY"
  48.    
  49.  
  50. # ---- END OF LOOP - DONE STATEMENT ----------------------------------------
  51.  
  52. done
  53.  
  54. # --------------------------------------------------------------------------
  55.  
  56. exit
  57.  
  58. # For comparison with original select builtin:
  59. select option in "${WORDS[@]}"; do
  60.  
  61.     [[ ! "$REPLY" = "0" ]] || { echo "Goodbye!" ; break; }
  62.     echo "You picked $option which is option $REPLY"   
  63.  
  64. done
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement