user2211678
user2211678

Reputation: 679

if statement checking regex expression not working

I have start learning shell programming today, what I am trying out is to do a simple option menu with 3 choices and if the user key in 1,2 or 3, it will be a valid input. anything besides 1,2,3 will be a invalid input.I have tried it out but it's not working as in nothing happened with my codes below. Please advice thanks.

 #!/bin/bash

 while  :
 do

    clear

       #display menu
       echo "1) choice 1"
       echo "2) choice 2"
       echo "3) choice 3"
       read -p "Enter choice: " choice
       regex = "[1-3]"
       if  [[ $choice -ne $regex ]]; then
           echo "Invalid input"
       else
           case $choice in 
           1) echo "this is choice one"
           2) echo "this is choice two"
           3) echo "this is choice three"
esac
     fi
done

Upvotes: 2

Views: 80

Answers (2)

devnull
devnull

Reputation: 123448

You're not comparing it as a regex. Say:

if [[ ! $choice =~ $regex ]]; then

Moreover, you shouldn't put spaces are = during assignment. Say:

regex="[1-3]"

From the manual:

An additional binary operator, ‘=~’, is available, with the same precedence as ‘==’ and ‘!=’. When it is used, the string to the right of the operator is considered an extended regular expression and matched accordingly

Upvotes: 3

user1907906
user1907906

Reputation:

Don't clear or you won't see anything.

Errors

Remove the blanks around =:

regex="[1-3]"

Your cases must end with ;;:

1) echo "this is choice one";;
2) echo "this is choice two";;
3) echo "this is choice three";;

Suggestions

Introduce an exit case:

'x') exit 0;;

The test [[ ]] is not needed if you use a default case as the last case:

*) echo "invalid input";;

Upvotes: 1

Related Questions