tags:

views:

289

answers:

2

Hi guys,

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.

+1  A: 

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
Jim Garrison
Thanks, it's tossing an syntax error near unexpected token `(' error right by the +([0-9])) I can't see any extra spaces or anything else. still looking.
Chasester
did you make sure to add the extglob? It won't work without it, since the +(...) syntax is enabled by extglob.
Jim Garrison
A: 

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.
Dennis Williamson
Thanks Dennis. I went without the extglob part - and it tests out fantastically.
Chasester