0

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?

4 Answers 4

1

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"
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

Comments

0

Something like:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.