Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash Case menu - dynamic choices

Tags:

bash

case

menu

I'm not sure what the policy is here on asking followup questions. So please excuse me if i'm breaking protocol. Earlier I was constructing a menu in bash ( Here )

And so far I've got it working really good. Code here.

while [[ 1 ]]
do
    cat -n "$dumpfile"
    read -p "Please make a selection, select q to quit: " choice
    case $choice in
            # Check for digits
    [0-9] )   dtvariable=$(sed -n "$choice"p "$dumpfile")
              $dtvariable            ;;
     q|Q)
         break
           ;;
      *)
           echo "Invalid choice"
           ;;
    esac
done

Except - that works great for menu items up to 9. The menu will be dynamic - could have 1 item, 20 items, or 197 items. I've tried changing [0-9] to be [0-9][0-9] to see if it would take 12. But it doesn't. Can anyone put me on the right path? I suppose I could just remove the [0-9] part and take anything that is not q. But wouldn't it be better to look for numbers?

Thank you in advance.

like image 595
Chasester Avatar asked Feb 28 '26 19:02

Chasester


2 Answers

I would do some validation on $choice:

case $choice in
     # Check for digits
    +([0-9]))
        lines=($(wc -l ))
        if (( choice > 0 && choice <= lines ))
        then
            dtvariable=$(sed -n "$choice"p "$dumpfile")
            $dtvariable            ;;
        fi
# etc.
like image 188
Dennis Williamson Avatar answered Mar 03 '26 15:03

Dennis Williamson


Here's what I got to work. The primary differences are the addition of shopt -s extglob, which turns on extended pattern matching, and the +([0-9]) pattern, which is the bash equivalent of regular expression [0-9]+

shopt -s extglob
while [[ 1 ]]
do
    read -p "Please make a selection, select q to quit: " choice
    case $choice in
            # Check for digits
    +([0-9]))  
         echo $choice ;;
     q|Q)
         break
           ;;
      *)
           echo "Invalid choice"
           ;;
    esac
done
like image 29
Jim Garrison Avatar answered Mar 03 '26 17:03

Jim Garrison



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!