-1

I am writing script, basically it's a calculator for very specific industrial procedure. I want to block alphanumeric input and allow only numerical input. How I do that???? I have used variable for user input but I want to restrict user to numerical input only, since it is a calculator.

For example:

cp=0

echo -n "Please Enter count % "

read cp

  • read the input in a loop. check that it's numeric. if not, print an error and return to the start of the loop. if it is numeric, continue with the rest of the script. – cas Feb 29 '16 at 09:33
  • e.g. a very simple version might look like: numeric=0; while [ $numeric -eq 0 ] ; do read -p "Please enter count % " cp ; if [[ $cp =~ ^[0-9]+$ ]] ; then numeric=1 ; else echo "Error: enter numeric value only" ; fi ; done – cas Feb 29 '16 at 09:43
  • Dear Sir, Thats wonderful.......... it gives me some more creative and interactive ideas. I have just checked your prescribed solution and it works owsam. Very much appreciated Sir.......... Thank you – Mudassir Mubin Baig Feb 29 '16 at 09:53

1 Answers1

0

You want to do something like this:

Read the input in a loop. Check that it's numeric. If not, print an error and return to the start of the loop. If it is numeric, continue with the rest of the script.

Here's a very simple implementation of that algorithm:

numeric=0
while [ $numeric -eq 0 ] ; do
  read -p "Please enter count % " cp
  if [[ $cp =~ ^[0-9]+$ ]] ; then
    numeric=1
  else
    echo "Error: enter numeric value only"
  fi
done
cas
  • 78,579