Read only number

Hi

I don't know, how read only number and when is on enter letter so I want write "Wrong enter "
Thank you and Sorry for my English

one way is to chck each lelemnt of the string to see if it is a numeric character

while :
do
  echo "enter a number: \c"
  read number
  len=${#number}
  testvar=$(echo "$number" | tr -dc '[:digit:]')   # remove non-numeric chars from $number
  if [[ $len -ne ${#testvar} ]] ; then  # if you had all numeric chars they would be the same length
      echo "$number is not a number"  # error message
  else
      break      #exit the loop
  fi
done 
#... more code goes here to work with the number

I'd say you may want to define what you mean by a "number" exactly. Is it just a positive integer ? Then jim's suggestion or the plain old regex /^\d+$/ or /[1]+$/ or /[2][0-9]*$/ should work with most languages/commands.

Do you allow negative numbers ? e.g. -123
Do you allow floating-point numbers ? e.g. 0.345, -123.456
How about preceding "+" sign or decimal point "." ? e.g. +12, .998
Or scientific notations ? e.g. 1e12

Depending on your requirement, you could go for more elaborate code in a scripting language or the shell.

tyler_durden


  1. 0-9 ↩︎

  2. 0-9 ↩︎

"Number" is positive integer

In that case, jim's script is good enough.

tyler_durden