phanI KY
phanI KY

Reputation: 111

Shell Script - Case statement which finds exactly numbers (without +,-,/,*)

Briefly,

I have a variable ($num) which contains random number(max.18), I need a case statement in shell (because along with checking number, I also have some alphabet conditions) which should validate the user input with the variable (must be less than $num).

Ex:

case $input in
...
1) ... ;;
2) ... ;;
...

so, here if I have only two conditions than I can write code like this, but my variable $num contains random number, how can I write case conditions which satisfies my below requirements.

The case condition should execute only if user inputs number between 1-$num no other number formats or symbols should not allowed.

Ex:

case $input in
[nN*]) ...
[aA*]) ...
 ...
 *) if echo "$input" | egrep '^\-?[0-9]+$'; then
    typeset -LZ num
    num="$input"
       if [ "$input" != "$num" ]; then
            echo "$input not a valid number"
       fi
    else
        echo "please choose proper choice option"
    fi
    ;;

This code works but I want a normal case condition which should satisfy my requirements like if we have two or three options we can simply write the code but what if we have random options (which may decrease or increase) how to write a case condition in that case.

Thanks!

Upvotes: 0

Views: 932

Answers (2)

fedorqui
fedorqui

Reputation: 289985

If the usage of a case is not compulsory, try and use some regex validation to have more control on what is allowed and what not:

[[ $input =~ ^[1-9][0-9]*$ ]]
#            ^  ^    ^   ^
#    beginning  |    |   end
#               |    any digit
#       a digit from 1 to 9

This checks that the data in $input contains a number that does not start with 0.

$ r=001
$ [[ $r =~ ^[1-9][0-9]*$ ]] && echo "yes"
$

$ r=1
$ [[ $r =~ ^[1-9][0-9]*$ ]] && echo "yes"
yes

$ r="3+1"
$ [[ $r =~ ^[1-9][0-9]*$ ]] && echo "yes"
$

You can then check if the number is lower than the stored one:

[ $r -le $num ]

All together:

$ num=15

$ r=5
$ [[ $r =~ ^[1-9][0-9]*$ ]] && [ $r -le $num ] && echo "yes"
yes

$ r=19
$ [[ $r =~ ^[1-9][0-9]*$ ]] && [ $r -le $num ] && echo "yes"
$

$ r="3+1"
$ [[ $r =~ ^[1-9][0-9]*$ ]] && [ $r -le $num ] && echo "yes"
$

Upvotes: 1

shas
shas

Reputation: 703

read -p "enter number" yournumber
re='^[0-9]+$'
if ! [[ $yournumber =~ $re ]] ; then
   echo "error: Not a number" >&2; exit 1
fi

This is only code rest of the things you need to do it.

Upvotes: 0

Related Questions