1

I am trying to validate user's input So input is a number not a string or null. using case I tried to do this

echo "input a number"
read num1

case $num1 in 
"" |*[a-zA-Z]*)
echo "please inter a valid number"
esac

echo "input 2nd number"
read num2



let sum=$num1+$num2
echo "$num1 + $num2=$sum"

But it didn't quite work. It gives me the warning about the input though -- And is there away to validate both variables at the sametime?

3 Answers3

1

To check both variables at once, you can concatenate and check.

Here is the part that changes:

case $num1$num2 in 
'' |*[!0-9]*)
    echo "please enter a valid number"
    exit
    ;;

You can also use exit to exit right after printing the error.

amisax
  • 3,025
  • Thanks @amisax But why it is not working for NULL? – user128174 Jul 07 '17 at 03:35
  • @user128174 , I have changed that part too. You need to use single quotes instead of double quotes in the case – amisax Jul 07 '17 at 04:15
  • Thanks again! Now what should I do to exit when the first input is is not a number or null? right now the program waits until the second input to be entered to print the error – user128174 Jul 07 '17 at 04:42
  • then you really want to do this one by one. The efficient ways to check the same can be seen here - https://stackoverflow.com/questions/806906/how-do-i-test-if-a-variable-is-a-number-in-bash – amisax Jul 07 '17 at 04:47
1

Using bash you can use a regular expression to validate the number:

#! /bin/bash
while [ -z "$REPLY" ]; do
    read -p "Enter a valid number: "
    if ! [[ "$REPLY" =~ ^[0-9]+$ ]] ; then
        echo Bad number: $REPLY
        REPLY=
    fi
done
echo A valid number: $REPLY

The program keeps reading input until the variable $REPLY is set by read. When the number is matched right against ^[0-9]+$ the loop is ended.

hschou
  • 2,910
  • 13
  • 15
0

You can define a custom function for doing that.

# func def.
isInt() {
    case ${1-} in '' | *[!0-9]* ) return 1 ;; esac
    return 0
}

# now use it as:
if isInt "$num1"; then
   echo "$num1 is a valid integer"
else
   echo "$num1 is not an integer"
fi

Note that case uses wildcards and not regexes for it's job.