Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

UNIX script type checking

Status
Not open for further replies.

Runt888

Programmer
Feb 17, 2003
3
US
Is there anyway to do type checking in a UNIX script? I need to check if a command line argument to my script is an integer. I'm using a while loop to get each character, but I don't know how to check if the character is an integer. I tried checking if it was between 0 and 9, but I got an error. If there's a way to get the ascii value, then I could check that. Any ideas? Thanks.

Kelly
 
Sure...

$ SOME_SCRIPT VAR1 VAR2 VAR3

$ SOME_SCRIPT TIME IS 4

SCRIPT:
#!/usr/bin/ksh -p

# TEST VAR3 for number only
CHKLET=`grep "[A-Za-z]" $3 > /dev/null 2>&1`
if [ $? -eq 0 ]
then
print "Variable 3 needs to be a number only...."
read PAUSE?"Press [Enter] to continue."
USAGE
fi

Something to that effect.
 
Thanks for the reply. I never thought about using grep. I have one question: what is the ? for in the if statement? Thanks.

Kelly
 
In the Korn shell, you can also force a variable to only allow integers. Try this...
[tt]
typeset -i INTEGER_VAR
[/tt]
 
$?: This is a special request to the shell for a Return Code. So if the RC is not equal to 0 for any command (unless otherwise stated in a man page), then it failed.

So if the grep found any letter then it would be successful and exit with a status of 0, otherwise it exits with a status of 1.
 
Ah...makes sense. Thanks for all the replies. SamBones, your solution sounds great, but I'm using the bash shell. Thanks though. And thank you pmcmicha for your solution.

Kelly
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top