Method 1:
#!/bin/bash
# SCRIPT: validinteger.sh
# USAGE: validinteger.sh [ Input value to be validated ]
# PURPOSE: validate integer input, allow negative integers also
#
# \\\\ ////
# \\ - - //
# @ @
# ---oOOo-( )-oOOo---
#
# Using the $? exit status variable or integer comparison operators, a
# script may test if a parameter contains only digits, so it can be
# treated as an integer.
#
#####################################################################
# Arguments Checking #
#####################################################################
if [ $# -eq 0 ]
then
echo -n "Enter input to test: "
read Number
else
Number=$1
fi
# You can also use bellow one liner
#[ $# -eq 0 ] && { echo -n "Enter input:";read Number; } || Number=$1
#####################################################################
# Main Script Starts Here #
#####################################################################
# Check the input is an integer or not
if [ $Number -ne 0 -o $Number -eq 0 2>/dev/null ]
then
# An integer is either equal to 0 or not equal to 0.
# 2>/dev/null suppresses error message.
echo "Supplied Input $Number is an Integer"
else
echo "Supplied Input $Number is not an Integer."
fi
# You can compare number itself also
# if [ $Number -eq $Number 2> /dev/null ]
# then
# echo "Supplied Input $Number is an Integer"
# else
# echo "Supplied Input $Number is not an Integer."
# fi
OUTPUT:
# chmod 755 validinteger.sh
# ./validinteger.sh -12345
Supplied Input -12345 is an Integer
# ./validinteger.sh 12345A
Supplied Input 12345A is not an Integer.
# ./validinteger.sh
Enter input to test: 876549
Supplied Input 876549 is an Integer
# ./validinteger.sh
Enter input to test: -345k123
Supplied Input -345k123 is not an Integer.
Method 2 :
#!/bin/bash
# SCRIPT: validinteger2.sh
# USAGE: validinteger2.sh [ Input value to be validated ]
# PURPOSE: validate integer input, allow negative integers also
#
#
# \\\\ ////
# \\ - - //
# @ @
# ---oOOo-( )-oOOo---
#
# In this method if you want to allow negative integers, it gets a
# tiny bit more complicated. You must have basic knowledge of string
# manipulation methods.
#
#####################################################################
# Arguments Checking #
#####################################################################
if [ $# -eq 0 ]
then
echo -n "Enter input to test: "
read Number
else
Number=$1
fi
#####################################################################
# Main Script Starts Here #
#####################################################################
# Check first character is -
if [ "${Number:0:1}" = "-" ] #extract first character
then
RemNumber="${Number:1}" #extract except first char
else
RemNumber="$Number"
fi
# You can extract substring using bellow method also
#if [ "$(echo $Number|cut -c 1)" = "-" ]
#then
# RemNumber=$(echo $Number|cut -c 2-)
#else
# RemNumber="$Number"
#fi
if [ -z "$RemNumber" ]
then
echo "Supplied Input $Number is not an Integer"
else
NoDigits="$(echo $RemNumber | sed 's/[[:digit:]]//g')"
if [ -z "$NoDigits" ]
then
echo "Supplied Input $Number is an Integer"
else
echo "Supplied Input $Number is not an Integer."
fi
fi
OUTPUT:
# chmod 755 validinteger2.sh
# ./validinteger2.sh -987612
Supplied Input -987612 is an Integer
# ./validinteger2.sh -A987612
Supplied Input -A987612 is not an Integer.
# ./validinteger2.sh
Enter input to test: -123456789
Supplied Input -123456789 is an Integer
# ./validinteger2.sh
Enter input to test: A234K78
Supplied Input A234K78 is not an Integer.
Method 3:
#!/bin/bash
# SCRIPT: validinteger3.sh
# USAGE: validinteger3.sh [ Input value to be validated ]
# PURPOSE: validate integer input, allow negative integers also
#
# \\\\ ////
# \\ - - //
# @ @
# ---oOOo-( )-oOOo---
#
# In this method input value validated using ASCII value range of
# numbers (48 - 57).
# Sample script provided by Bond, Thank you Bond.
#
#####################################################################
# Arguments Checking #
#####################################################################
if [ $# -eq 0 ]
then
echo -n "Enter input to test: "
read Number
else
Number=$1
fi
# You can also use bellow one liner
#[ $# -eq 0 ] && { echo -n "Enter input:";read Number; } || Number=$1
#####################################################################
# Main Script Starts Here #
#####################################################################
# Check first character is - ?
# This is another method to extract substring using Substring Removal
# method.
if [ "${Number%${Number#?}}" = "-" ] #extract first char
then
RemNumber="${Number#?}" #extract all except first char
else
RemNumber="$Number"
fi
if [ -z "$RemNumber" ]
then
echo "Supplied Input $Number is not an Integer"
else
Length=${#RemNumber} # Counting length of the string
for ((i=0; i < Length; i++))
do
char=${RemNumber:$i:1} # Reads character one by one
code=`printf '%d' "'$char"` # Get ASCII value of char
# Compare code with ASCII value range of Intergers ( 48 - 57 )
if [ $code -lt 48 ] || [ $code -gt 57 ]
then
echo "Supplied Input $Number is not an Integer"
exit 1
fi
done
echo "Supplied Input $Number is an Integer."
fi
OUTPUT:
$ sh validinteger3.sh -1234
Supplied Input -1234 is an Integer.
$ sh validinteger3.sh -12-12
Supplied Input -12-12 is not an Integer
$ sh validinteger3.sh
Enter input to test: -
Supplied Input - is not an Integer
$ sh validinteger3.sh
Enter input to test: 123a456
Supplied Input 123a456 is not an Integer
Sunday, December 19, 2010
Posted by venu k
82 comments | 11:25 AM
Subscribe to:
Post Comments (Atom)
Hi Venu,
ReplyDeleteJust another version to server the same purpose using comparison with ASCII chart:
#!/bin/bash
echo -e "\nScript to validate whether input is an Interger value of not"
if [ $# -ne 1 ]
then
echo "Usage: $0 [Input Value to be validated]"
exit
fi
str="$1"
cnt=${#str} # Counting the length of string fetched
for ((i=0; i < cnt; i++))
do
char=${str:$i:1} # Reading one character at a time from the input string
code=`printf '%d' "'$char"` # Echo the ASCII value of character
echo "code: " $code
if [ $code -lt 48 ] || [ $code -gt 57 ] # Comparing the ASCII value range of Intergers ( 48 - 57 )
then
if [ $code -ne 45 ] # To accept the negative integer value as well
then
echo -e "Input is not an integer value\n"
exit
fi
fi
done
echo -e "\nThe input is valid integer value\n"
Hi Bond,
ReplyDeleteYour idea is good, but above script has a mistake.
$ sh validintegernum.sh -12-12
Script to validate whether input is an Integer value of not
code: 45
code: 49
code: 50
code: 45
code: 49
code: 50
The input is valid integer value
It accepts hyphen any where. I rectified it and posted as method 3.
From Method 1, how would I adapt
ReplyDeleteif [ $Number -ne 0 -o $Number -eq 0 2>/dev/null ]
so that it worked in a while loop so that I could keep prompting the user for a number until they entered one?
the ultimate numeric testing:
ReplyDelete#!/bin/bash
n="$1"
echo "Test numeric '$n' "
if ((n)) 2>/dev/null; then
n=$((n))
echo "Yes: $n"
else
echo "No: $n"
fi
That accepts undesirable mathematical expressions as input too.
DeleteE.g. try evaluating the string "1234 != 4321".
Samples:
ReplyDeleteTest numeric 'foo'
No: foo
Test numeric '2'
Yes: 2
Test numeric '-7'
Yes: -7
Test numeric '+8'
Yes: 8
Test numeric '2**7'
Yes: 128
Test numeric '3+4+5'
Yes: 12
Test numeric '20%14'
Yes: 6
Test numeric '+'
No: +
Test numeric '-'
No: -
Test numeric '%'
No: %
Maybe better use something like this:
ReplyDelete[[ $1 =~ ^-{0,1}[0-9]+$ ]] && echo 'It's a integer'
or
[[ $1 =~ ^-{0,1}[[:digit:]]+$ ]] && echo 'It's a integer'
or
[[ $1 =~ ^-{0,1}[[:xdigit:]]+$ ]] && echo 'It's a hex integer'
@Anonymous the 1st
ReplyDeleteGreat, but doesn't detect 0
if ((${n}1)) 2>/dev/null
works better to me :)
Alex: Your logic too has bug. It doesnt detect null or space.
Deletefor example n="" or n=" "
case $1 in
ReplyDelete*[!0-9]* | "") echo Not integer ;;
*) echo Integer ;;
esac
The simplest and most elegant solution is the section commented out in Method 1 above, but with the variable in quotes to take care of null value:
ReplyDelete# You can compare number (to) itself also
if [ "$Number" -eq "$Number" 2> /dev/null ]
then
echo "Supplied Input $Number is an Integer"
else
echo "Supplied Input $Number is not an Integer."
fi
This takes care of all the possible variations (including "-12-12") and uses a test that is absolutely specific - "Can we carry out arithmetic operations on the variable or not?". If we can then it is a number, otherwise it isn't.
Verification and validation techniques applied throughout the development process enable you to find errors before they can derail your project.
Deletethey are involved in lot of process improvements which will actually help the clients to deliver best software.
software validation
hi ,
ReplyDeleteI have doubt in passing input values to the script.please some one help me?
I just wanted to comment your blog and say that I really enjoyed reading your blog post here.
ReplyDeleteIt was very informative and I also digg the way you write!I also provide this service u can visit my site.
software validation
I really like examining and also following ones write-up when i locate them incredibly beneficial and also fascinating.
ReplyDeleteThat write-up is usually just as beneficial along with fascinating.Verification and Validation both are independent type of testing. Obviously,
If we look both of these activities as a whole, we can also call it testing.
software validation
I stumbled upon this topic via Google. Very interesting view on subject. Thanks for sharing.
ReplyDeleteLinux : positive and negative sides
ReplyDeleteJust one way that you can improve your chances of success. After All things considered, these devices are accessible so you ought to exploit them when you can.best project management app
ReplyDeletethere are other more included alternatives too. With a CMS, you don't need to know HTML, and you can set up a page rapidly and effortlessly.content management system
ReplyDeleteSuch a great post and its give me big piece of information about math scripts ad its really helped him thanks for share it project management homework help .
ReplyDeleteToday i learned a new concept which is help me to update new things and i like those math script what you have posted.
ReplyDeleteabap training in chennai
Its an extremely helpful and osm guide and helpful info cover-all that things.I am a large lover of the website. I love how a post is offered. Aspire to discover selenium internet motorist . For more info on this go here
ReplyDeleteNice post, Thanks for sharing such a useful post.
ReplyDeleteseo training in Chennai
It's quite helpful to learn about integeration method using shell script.
ReplyDeleteRegards,
Software testing training|Software training|Software testing training in chennai
Informative post. Keep sharing such a useful post.
ReplyDeleteSocial Media Marketing Courses in Chennai
MSBI accreditations being the best and most eminent virtualization confirmations, is viewed as the pioneer advancements and driving supplier of virtualization items and answers for organizations and IT industry. | PHP Training | VMWare Training | MSBI Training | Chef Training | OpenStack Training
ReplyDeleteThanku for this details about validate integer nice posts..
ReplyDeletesap fiori training in hyderabad
validate integer input nice posts..
ReplyDeleteSAP Hana training in hyderabad
Great article. This is very useful post. Thanks for sharing.
ReplyDeletePHP Course in Chennai
Wonderful post. I learned some new things. Thanks for sharing.
ReplyDeleteseo training in chennai
really a good post
ReplyDeleteBest Selenium Training in Chennai | Android Training in Chennai | Java Training in chennai | Webdesigning Training in Chennai
Great article. Keep sharing such a useful post.
ReplyDeleteweb designing course in chennai
great article.you have post very informative blog.thank you for sharing this blog.
ReplyDeletecodedUI training
Helpful post.Thanks for taking time to share this informative post to my vision.
ReplyDeleteRegards,
VMware courses in Chennai | VMware Training institutes in Chennai
Excellent Blog.Your post is nice and informative. Final Year Project Center in Chennai | BE Project Center in Chennai
ReplyDeleteWonderful post. I learned some new things. Thanks for sharing.
ReplyDeletejava training in chennai
Thanks for sharing your interesting blog of post.
ReplyDeleteJava Training Institute in Chennai | Best Java Training Institute in Chennai
This comment has been removed by the author.
ReplyDeleteThanks for Posting the nice blog. It was so helpful to me.
ReplyDeleteFinal Year Project Center in Chennai | IEEE Project Center in Chennai
Useful post.Thanks fro taking time to share this post.Continue sharing more like this,
ReplyDeletePlacement Training institutes | Placement courses in Chennai | Training come placement in Chennai
Informative post. keep updating regularly. HP LR Training Institute in Chennai | Android Training Institute in Chennai.
ReplyDeleteThe best thing is that your blog really informative thanks for your great information!
ReplyDeleteERP Software Solutions in Chennai
Your Blog was really awesome with impressive content..Thanks for sharing,keep updating..
ReplyDeleteMCSE Certification Training with Placement in Chennai | MCSE Exam Center in Chennai | MCSE Certification Training Institute in Chennai | Online Training Center in Chennai
Thanks for sharing this information, Hi we at Colan Infotech Private Limited , a company which is Situated in US and India, will provide you best service and our talented team will assure you best result and we are familiar with international markets, We work with customers in a wide variety of sectors. Our talented team can handle all the aspects of custom application development, we are the best among the dot net development companies in Chennai . asp .net web development company We have quite an extensive experience working with asp .net development services. we are the only asp.net web development company which offer custom services to a wide range of industries by exceeding our client’s expectations. You can even interact directly with the team regarding your project, just as you would with your in-house team. hire asp.net programmers to achieve your dream product.
ReplyDeleteCustom application development company, asp.net development companies, asp .net web development company,Hire asp .net programmers,asp.net web development services,dot net development companies in chennai Hire asp .net programmers/ hire asp .net developer . We are the best asp .net development company providing top notch asp .net development services Hire asp .net programmers/ hire asp .net developer . We are the best asp .net development company providing top notch asp .net development services.
ReplyDeleteThanks for posting useful information.You have provided an nice article, Thank you very much for this one. And i hope this will be useful for many people.. and i am waiting for your next post keep on updating these kinds of knowledgeable things...Really it was an awesome article...very interesting to read..
please sharing like this information......
Android training in chennai
Ios training in chennai
ReplyDeleteIt's interesting that many of the bloggers your tips helped to clarify a few things for me as well as giving.. very specific nice content. And tell people specific ways to live their lives.Sometimes you just have to yell at people and give them a good shake to get your point across.
Web Design Company
Web Development Company
Mobile App Development Company
Good and nice information, thanks for sharing your views and ideas.. keep rocks and updating
ReplyDeleteSoftware Testing Training in chennai | Software Testing Training institute in chennai
Hi, i really enjoyed to read your article.. i got clear idea through your views and ideas.. thanks for sharing your post..
ReplyDeleteAndroid Training in chennai
IOS Training in chennai
Dot Net Training in chennai
you explained the concept of shell script. its really helpful from me..
ReplyDeleteNo.1 Software Testing Training Institute in Chennai | Best Selenium Training Institute in Chennai
These ways are very simple and very much useful, as a beginner level these helped me a lot thanks fore sharing these kinds of useful and knowledgeable information.
ReplyDeleteTexting API
Text message marketing
Digital Mobile Marketing
Sms API
Sms marketing
Nice and informative post..Thanks for sharing this helpful blog.
ReplyDeleteBest BE | B.Tech Project Center in Chennai | ME | M.Tech Project Center in Chennai | Best IT Project Center in Chennai
Thank you for the post...
ReplyDeleteQlikView Training in Chennai
Informatica Training in Chennai
Python Training in Chennai
AngularJS Training in Chennai
Best AngularJS Training in Chennai
Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.
ReplyDeleteJava Training In Bangalore
Useful information. i am looking SAP HANA Online Training with real time project.
ReplyDeleteInformative post.thanks for sharing valuable information from your blog..Web Designing Training Institute in Chennai | Java Script Training in Chennai| HTML & CSS Training in Velachery
ReplyDeleteReally great post, Thank you for sharing This knowledge.Excellently written article, if only all bloggers offered the same level of content as you, the internet would be a much better place. Please keep it up!
ReplyDeleteB.Com Project Center in Chennai | B.Com Project Center in Velachery
Your blog was so informative., I heartily Thank you for sharing such a useful blog.,Web Designing Training Institute in Chennai | Bootstrap Training in Chennai| HTML & CSS Training in Velachery
ReplyDeleteReally an amazing article..I gained more information from your post..PHP Projects Center in Chennai | PHP Projects Center in Velachery
ReplyDeleteVery good informative article. Thanks for sharing such nice article, keep on up dating such good articles.
ReplyDeleteAustere Technologies | Best Cloud Solution services | Austere Technologies cloud Solutions
REALLY VERY EXCELLENT INFORMATION. I AM VERY GLAD TO SEE YOUR BLOG FOR THIS INFORMATION. THANKS FOR SHARING. KEEP UPDATING.
ReplyDeleteNO.1 SYSTEM INTEGRATION SERVICES | SYSTEM INTEGRATION MIDDLEWARE | MASSIL TECHNOLOGIES
Excellent post. I have read your blog it's very interesting and informative. Keep sharing.
ReplyDeleteNo.1 Image Processing Project Center in Chennai | No.1 Image Processing Project Center in Velachery
Great information. Keep updating.
ReplyDeleteBest IT Security Services | Austere Technologies
Very good informative article. Thanks for sharing such nice article, keep on up dating such good articles.
ReplyDeleteBest IT Security Services | Austere Technologies
Wonderful post. I am learning so many things from your blog.keep posting..Summer Course in Thiruvanmiyur | Summer Course in Chennai
ReplyDeleteGood to know such things, sometimes they can be useful.
ReplyDeleteThank you for this Useful Blog!
ReplyDeleteArduino Training in Chennai | Android Training in chennai
Interesting post! This is really helpful for me. I like it! Thanks for sharing!
ReplyDeletec sharp training in chennai | asp .net training in chennai
A decent path for you to take in more about screenplay composing is to watch completed items in real life. On the off chance that you need to be a content author for TV appears, assault yourself with TV programs that you need to make.how to write a screenplay
ReplyDeleteGreat article, really very helpful content you made. Thank you, keep sharing.
ReplyDeleteBest Degree Colleges Hyderabad | Avinash College of Commerce
I am really happy with your blog because your article is very unique and powerful for new reader.
ReplyDeleteSelenium Training in Chennai
Thank you for sharing this valuable information. But get out of this busy life and find some peace with a beautiful trip book best Andaman honeymoon packages
ReplyDeleteThanks for sharing the information, Salesforce experts a lot of openings in multi-level companies, for more information n
ReplyDeleteSalesforce Training
Salesforce certification Training program
Salesforce Online Training in Bangalore
I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.
ReplyDeleteEmbedded System training in Chennai | Embedded system training institute in chennai | PLC Training institute in chennai | IEEE final year projects in chennai | VLSI training institute in chennai
Hi Thanks for the nice information its very useful to read your blog. We provide best Find All Isfs Courses
ReplyDelete"
ReplyDeleteAt the point when all activities and slimming down stage gets fizzled, Keto Primal works splendidly to give the coveted results by giving a thin and sharp body appearance since it is a characteristic craving boosting fat buster. The supplement additionally limits the nourishment desires or enthusiastic eating of people where they would encounter less appetite feel and that would offer them to stay in controlled calorie admission.
The supplement attempts to influence a person to go fit as a fiddle and carry on with a sound and a la mode way of life. The weight reduction process that begins after the admission of the pills go normally, and you may encounter the results inside 2-3 weeks of time. The expansion of every common concentrate here attempts to support the stomach related framework and furthermore clean the colon framework to stay free from hurtful poison squander. It supports the digestion level and gives a lift to vitality and stamina level where you would have the capacity to exercise more without getting worn out and stay dormant way of life. Visit for more informations:
Keto Primal
Health Care 350"
"I like this post,And I guess that they having fun to read this post,they shall take a good site to make a information,thanks for sharing it to me.
ReplyDeleteRead more here:
kim kardashian sex tape
porn sex video hd
mia khalifa sex video
sunny leone sexy movie"
Progressions in innovation have made life a great deal less demanding for every single one of us. This is valid for all parts of our lives, even in the region of our funds. Liquidating checks, for instance, is a considerable measure less demanding these days than it was previously.
ReplyDeleteusacheckcashingstore.com/carson
Excellent informative blog, keep for sharing.
ReplyDeleteBest System Integration services | Massil Technologies
Excellent informative blog, keep sharing.
ReplyDeleteCA institute in hyderabad | Avinash College of Commerce
Excellent informative blog, Thanks for sharing.
ReplyDeletecs institutes in hyderabad | Avinash College of Commerce
Thanks for sharing this information admin, it helps me to learn new things. Continue sharing more like this.
ReplyDeleteAWS Training in Chennai
AWS Training near me
AWS course in Chennai
AWS Certification in Chennai
RPA courses in Chennai
DevOps Training in Chennai
Angularjs Training in Chennai
This comment has been removed by the author.
ReplyDelete