Basic number checking problem

Hello all

I am having problems using a bash script to read the input from the user and checking that its a valid number. I only want the user to input a maximum of a 3 number string (321 , 521 , 871 etc.). Anything longer or that includes a chararcter or symbol will display an error message.

heres what i have got so far

 
read input
 
        for ((x=1;x<4;x++)){
        v=`echo $input | cut -c $x`
        if [ $v !-eq (0-9) ]
        then
        echo "error"
        else
        continue
        fi
        }

 

works in bash:

for (( i=1 ; i<4 ; i++))
 do  
  read a 
  echo $a | egrep -w "[0-9]{1,3}" || echo "wrong input"
 done

Hi ChrisHoogie,

grep will make it much easier!

read input
if egrep -q '^[0-9]{1,3}$' <<< "$input"; then
    your command here
else
    echo error
fi

---------- Post updated at 11:14 ---------- Previous update was at 11:09 ----------

Hi funksen,
Watch for your command, it will still accept the following inputs:
1 e24
abc 123

yep you are right, I expected an input of one string without space

the loop is not necessary, thought he want to check three inputs

Cheers for that chebarbudo, works a treat :smiley:

Funksen the for loop was there to break up the input into characters and check them one by one. Sorry for the confusion but thank you anyway :slight_smile:

Hey ChrisHoogie,

Depending on the rest of your script, you can put everything in one line :

read input
egrep -q '^[0-9]{1,3}$' <<< "$input" || { echo "$(basename "$0"): Wrong input" >&2; exit 1; }
the
rest
of
your
script

cheers chebarbudo :smiley: learning new stuff everday, slowly becoming a script junkie

I have been doing some reading on redirection and still can not find any clear meaning of <<< Can you explain what the third < does

Is there any other reason than to be cool for not using `if (x>999)'? =P

(And that's my first post, talking about something i have no clue about... Doh.)

Hi TaylanUB,

What exactly do you want to check with that?
The proper syntax in shell would be:

if ($x>999); then
    something
fi

and it will fail in most cases.
Have you only tried your command?

terminal80:~# x=abc
terminal80:~# if ($x>999); then echo wrong; else echo right; fi
-bash: rty: command not found
right
terminal80:~# x=123
terminal80:~# if ("$x">999); then echo wrong; else echo right; fi
-bash: 123: command not found
right