Search code examples
bashshellubuntu

Check for invalid input in a menu


I am making a script where the user selects a number 1-5 and it will loop until the user enters 5. I don't want to use the exit command. I wanted to check to make sure the user doesn't enter anything but 1-5 and if they do display invalid input.

any help would be appreciated

#!/bin/bash
  PS3='Please enter your choice: '
options=("1.Move empty files" "2.Check file size" "3.Which files is newer" "4.File check rwx" select opt in "${options[@]}")


 while($opt != 5); do
   case $opt in

        "Option 1")
          echo "you chose choice 1"
          ;;
        "Option 2")
          echo "you chose choice 2"
          ;;

        "Option 3")


     echo "you chose choice 3"
    ;;
 "Option 4")
  echo "you chose choice 3"
               ;;
          "Option 5")
           break
           ;;
   ) echo invalid input;;

Solution

  • You seem confused. I don't even know where to begin correcting whatever misconceptions you have about how this works

    In your original code the way you set options is unlikely to do anything useful.

    options=("1.Move empty files" "2.Check file size" "3.Which files is newer" "4.File check rwx" select opt in "${options[@]}"
    printf '%s\n' "${options[@]}"
    

    This will emit

    1.Move empty files
    2.Check file size
    3.Which files is newer
    4.File check rwx
    select
    opt
    in
    

    The select command will not have been executed.

    Here's something that does what you seem to want.

    options=(
        'Move empty files'
        'Check file size'
        'Which file is newer'
        'File check rwx'
    )
    
    PS3='Please enter your choice: '
    select opt in "${options[@]}"; do
        [[ -n $opt ]] && break || {
            echo "invalid input"
        }
    done
    echo "user chose '$opt'"
    

    You could go with a while and case solution and get nearly the same results e.g.:

    options=(
        'Move empty files'
        'Check file size'
        'Which file is newer'
        'File check rwx'
    )
    
    for (( i=0 ; i < ${#options[@]}; i++ )); do
        printf '%d) %s\n' $((i+1)) "${options[$i]}"
    done
    while true; do
        read -p 'Please enter your choice: ' opt
        case "$opt" in
            [0-3])
                opt="${options[opt-1]}"
                break
            ;;
            *)
                echo "invalid input"
            ;;
        esac
    done
    
    echo "user chose '$opt'"
    

    But you don't need both and, as you can see, using select is much simpler.