|
|||||||
| Forums | Search Forums | Register | Forum Rules | Man Pages | Albums | FAQ | Members | Calendar | Search | Today's Posts | Mark Forums Read |
| Shell Programming and Scripting Post questions about KSH, CSH, SH, BASH, PERL, PHP, SED, AWK and OTHER shell scripts and shell scripting languages here. |
|
|
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
validate number range
Hi
If I want to read user input and want to validate if it is a numeric number in some range of 1-100 what would be the best way? Sabina |
| Sponsored Links | ||
|
|
#2
|
||||
|
||||
|
You need to tell us which shell and what system. But for ksh this should work
print -n "enter number - " read val if [[ $val -ge 1 && $val -le 100 ]] ; then |
| Sponsored Links | ||
|
|
#3
|
|||
|
|||
|
hi
I am using bourne shell. I used your script it works as long as I enter a number. I want it to fail if I enter a string by mistake. Thanks for your reply. Sabina |
|
#4
|
||||
|
||||
|
Code:
print -n "enter number - "
read val
echo $val | grep "[a-zA-Z]"
if test $? -ge 1
then
if [[ $val -ge 1 && $val -le 100 ]] ; then
print "OK"
else
print "NOT in 1-100 range"
fi
else
print "Not a number"
fi |
| The Following User Says Thank You to bhargav For This Useful Post: | ||
LinuxRacr (05-20-2011) | ||
| Sponsored Links | |
|
|
#5
|
||||
|
||||
|
A slight variation on bhargav's script to ensure that only numeric digits are passed, and symbols as well as letters are rejected.... Code:
#!/bin/sh
echo "Enter number"
read val
if echo $val | egrep '^[0-9]+$' >/dev/null 2>&1
then
if [ $val -ge 1 -a $val -le 100 ]; then
echo "OK"
else
echo "Out of range"
fi
else
echo "Not a number"
fi
exit 0Cheers ZB |
| The Following User Says Thank You to zazzybob For This Useful Post: | ||
LinuxRacr (05-20-2011) | ||
| Sponsored Links | |
|
|
#6
|
|||
|
|||
|
hi Zb and bhargav
Thanks a lot for your time. It was really useful. Sabina |
| Sponsored Links | ||
|
![]() |
| Thread Tools | Search this Thread |
| Display Modes | |
More UNIX and Linux Forum Topics You Might Find Helpful
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| how can I detect number series range | kocaturk | Shell Programming and Scripting | 8 | 12-05-2011 05:18 AM |
| Number range for SSNs | lyoncc | Shell Programming and Scripting | 1 | 01-22-2011 11:12 AM |
| extract number range from a file | jimmy_y | Shell Programming and Scripting | 1 | 06-03-2010 05:17 AM |
| PERL: Simple reg expr validate 6 digits number | BufferExploder | Shell Programming and Scripting | 2 | 09-10-2008 11:15 AM |
| Cutting number from range in xml file | nir_s | Shell Programming and Scripting | 4 | 07-25-2005 02:38 AM |
|
|