POP
POP

Reputation: 3

Validate input in bash script

I have a code to find the area of a rectangle by giving the width and height.

echo -n "Enter width: "
read width

echo -n "Enter height:"
read height

echo "Area of rectangle $(echo "$height*$width" | bc) sqcm"

How can I make it so that only a number can be entered and, otherwise, an error display?

Upvotes: 0

Views: 1115

Answers (4)

Alim Özdemir
Alim Özdemir

Reputation: 2624

Something like:

echo $width | grep -E -q '^[0-9]+$' || echo "numeral expected!"

Upvotes: 0

fedorqui
fedorqui

Reputation: 289495

Since you are reading input twice, I would use a function to check it. This way you do not repeate code.

This checks whether input contains just digits and at least one. Otherwise, it keeps asking for the input:

myread () {
  while :                     # infinite loop
  do
     read value
     [[ $value =~ ^[0-9]+$ ]] && echo "$value" && return  #return value if good input
  done
}

echo -n "Enter width: "
width=$(myread)             #call to the funcion and store in $width

echo -n "Enter height: "
height=$(myread)            #call to the funcion and store in $height

echo "Area of rectangle $(echo "$height*$width" | bc) sqcm"

Upvotes: 1

Srini V
Srini V

Reputation: 11355

You can do some thing like thi

    if [[ -n "$width" ]] ; then

        nodigits="$(echo $width| sed 's/[[:digit:]]//g')"

        if [[ ! -z $nodigits ]] ; then

            print "Invalid number format! Only digits, no commas, spaces, etc." 

        fi 
    fi

Upvotes: 0

Noufal Ibrahim
Noufal Ibrahim

Reputation: 72745

You could perhaps use grep to check but really bash (and shell in general) is a bad choice of language if you want these kinds of checks.

Upvotes: 0

Related Questions