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 Answers 3

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.

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.

4
  • Thanks @amisax But why it is not working for NULL? Commented Jul 7, 2017 at 3:35
  • @user128174 , I have changed that part too. You need to use single quotes instead of double quotes in the case Commented Jul 7, 2017 at 4: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 Commented Jul 7, 2017 at 4:42
  • then you really want to do this one by one. The efficient ways to check the same can be seen here - stackoverflow.com/questions/806906/… Commented Jul 7, 2017 at 4:47
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.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.