Ask Dave Taylor
  • Facebook
  • Instagram
  • Linkedin
  • Pinterest
  • Twitter
  • YouTube
  • Home
  • YouTube Videos
  • Top Categories
  • Subscribe via Email
  • Ask A Question
  • Meet Dave
  • Home
  • Linux Help
  • Test for valid numbers in a Bash shell script?

Test for valid numbers in a Bash shell script?

October 25, 2010 / Dave Taylor / Linux Help, Linux Shell Script Programming / No Comments

In a different discussion on this site [see Redirecting input in a shell script] a visitor commented that “I was too busy trying to make sure the above post made sense that I forgot to ask for help. If you can, please post examples of how I can make the second argument a requirement and evaluate if it is a number. Thank you in advance!”

There are simple solutions to both issues, and I really dig into these in my popular book Wicked Cool Shell Scripts (pay special attention to script #5, validating numeric input), so I’m going to crib a bit from that script to show you how I solved this…
First off, it’s pretty easy to require a positional parameter be specified, either by checking the number of arguments given (with $#) or by simply testing the specific positional parameter for a non-null value (e.g. $2).
Really, all you do is test if it’s specified, then have whatever code subsequent that you want. In this case, I strongly suggest a “usage” message along with whatever error you’d like. In fact, my scripts almost always have a usage message with details about parameters and expected input formats if you skip any input at all.
Back to the test, though! The first test would look like this:

if [ $# -ne 2 ] ; then…

and the second test, if you prefer just looking at the individual parameter, would look like this:

if [ -z “$2” ] ; then

(check the man page for ‘test’ if you want to know what the -z flag does, but if you’re writing shell scripts, it should already be something you’re familiar with. 🙂
The bigger question is how you validate for numbers only, and my general approach for testing argument value is to basically push the input through a ‘strainer’ and see what comes out the other end.
In this case, I’m going to use “sed” to replace all digits with null and see if the remainder is itself null (meaning that the argument was just digits) or not.
First step, to filter out the digits:

nodigits=”$(echo $testvalue | sed ‘s/[[:digit:]]//g’)”

Now to test the result:

if [ ! -z $nodigits ] ; then
  echo “Invalid number format! Only digits, no commas, spaces, etc.” >&2
  exit 1
fi

If you want to allow negative integers, it gets a tiny bit more complicated, but you just have to test the very first character to see if it’s a minus sign, and if so, remove it. I’d suggest using “cut -c1” to get the first character, and “cut -c2-” for everything after that first digit. Something like this:

if [ “$(echo $2 | cut -c1)” = “-” ] ; then …

Of course, in the book I have a much fancier solution that I prefer, but it’s hard to remember when you’re whipping out a script to accomplish a specific task:

if [ “${number%${number#?}}” = “-” ] ; then # first char ‘-‘ ?

In any case, I hope that helps clarify how to both force a parameter and then test it to see if it’s a valid number or not. Oh, and in the book I have a really complicated script function that tests for valid real / floating point numbers. Considerably more complex…

Let’s Stay In Touch!

Never miss a single article, review or tutorial here on AskDaveTaylor, sign up for my fun weekly newsletter!
Name: 
Your email address:*
Please enter all required fields
Correct invalid entries
No spam, ever. Promise. Powered by FeedBlitz
Please choose a color:
Starbucks coffee cup I do have a lot to say, and questions of my own for that matter, but first I'd like to say thank you, Dave, for all your helpful information by buying you a cup of coffee!

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Search

Recent Posts

  • How Can I Delete My Phone from My Mom’s Mitsubishi Outlander?
  • How Do You Lower the Volume on Apple Watch Alerts?
  • How do I Schedule a Google Meet call with Colleagues?
  • How Can I Add My Pronouns to my Instagram Account Profile?
  • Possible to Pair Bluetooth Headphones with my Vizio TV?

On Our YouTube Channel

ONFORU Outdoor Bluetooth LED Light-Up Lantern Speakers -- REVIEW

Google Pixel 6a Budget Android Smartphone -- DEMO & REVIEW

Categories

  • AdSense, AdWords, and PPC Help (106)
  • Amazon, eBay, and Online Shopping Help, (161)
  • Android Help (201)
  • Apple iPad Help (145)
  • Apple Watch Help (53)
  • Articles, Tutorials, and Reviews (344)
  • Auto Tech Help (12)
  • Business Advice (199)
  • Chrome OS Help (25)
  • Computer & Internet Basics (764)
  • d) None of the Above (165)
  • Facebook Help (383)
  • Google, Chrome & Gmail Help (180)
  • HTML & Web Page Design (245)
  • Instagram Help (48)
  • iPhone & iOS Help (607)
  • iPod & MP3 Player Help (173)
  • Kindle & Nook Help (93)
  • LinkedIn Help (85)
  • Linux Help (166)
  • Linux Shell Script Programming (87)
  • Mac & MacOS Help (894)
  • Most Popular (16)
  • Outlook & Office 365 Help (26)
  • PayPal Help (69)
  • Pinterest Help (53)
  • Reddit Help (18)
  • SEO & Marketing (81)
  • Spam, Scams & Security (92)
  • Trade Show News & Updates (23)
  • Twitter Help (217)
  • Video Game Tips (66)
  • Web Site Traffic Tips (62)
  • Windows PC Help (921)
  • Wordpress Help (204)
  • Writing and Publishing (72)
  • YouTube Help (46)
  • YouTube Video Reviews (159)
  • Zoom, Skype & Video Chat Help (57)

Archives

Social Connections:

Ask Dave Taylor


Follow Me on Pinterest
Follow me on Twitter
Follow me on LinkedIn
Follow me on Instagram


AskDaveTaylor on Facebook



microsoft insider mvp


This web site is for the purpose of disseminating information for educational purposes, free of charge, for the benefit of all visitors. We take great care to provide quality information. However, we do not guarantee, and accept no legal liability whatsoever arising from or connected to, the accuracy, reliability, currency or completeness of any material contained on this site or on any linked site. Further, please note that by submitting a question or comment you're agreeing to our terms of service, which are: you relinquish any subsequent rights of ownership to your material by submitting it on this site. Our lawyer says "Thanks for your cooperation."
© 2022 by Dave Taylor. "Ask Dave Taylor®" is a registered trademark of Intuitive Systems, LLC.
Privacy Policy - Terms and Conditions - Accessibility Policy