|
|
Test for valid numbers in a Bash shell script?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...
More Useful Shell Script Programming Articles:
✔ Secretly capture screenshots on my Mac?
When I used to work on a Linux system, there was a utility we had that would let me take screen captures every...
✔ Parsing "id" strings in a Shell Script?Hello Dave. I need a Bash shell script that creates a directories with the group names automatically when user logs in to the...
✔ Copy and Paste from the Mac OS X Command Line?I am constantly running commands in Terminal.app on my MacBook and then copying and pasting the results into email messages or documents. Yes,...
✔ Script to test line lengths for Twitter compatibility?I've been tasked with writing a series of tweets for a Black Friday marketing campaign and am finding it a bit tricky because...
✔ Shell script to convert lowercase to title case?As part of a project I'm working on, I find myself deep in a Linux shell script, needing to have a subroutine that...
Let's stay in touch!
Sign up for my weekly AskDaveTaylor Newsletter and you'll receive even more tech and gadget help
right to your inbox, along with exclusive news and industry updates. It's good stuff. I promise!
Categorized:
Shell Script Programming
,
Unix and Linux Help
(Article 9618,
Written by Dave Taylor)
Tagged: bash shell script, linux scripting, programming, shell script programming Previous: How can I get more space on my Windows hard disk? Next: How do binary numbers work? Reader Comments To Date:
Rather amazingly, there are no comments on this article yet.
I do have a comment, now that you mention it!Check This Out Too... |
Recent Entries
Look for Answers
Recommended
All Our Categories
Apple iPad Help
Articles and Reviews Auctions and Online Shopping Blogs and Blogging Building Web Site Traffic Business and Management Computer and Internet Basics d) None of the Above Facebook Help Google Gmail Help Google Plus Help HTML, JavaScript and Web Site Programming Industry News and Trade Shows iPhone and Cell Phone Help iPod, Sony PSP and MP3 Player Help Kindle Fire Help Mac OS X Help Pay Per Click (PPC) Advertising Pinterest Help Search Engine Optimization (SEO) Shell Script Programming Tech Support Video Help The Writing Business Twitter, LinkedIn and Social Network Help Unix and Linux Help Video Game Tips and Help Windows PC Help Find Me on Google+ ADT on G+ |