Results 1 to 4 of 4
Is there a way in bash to check if a variable is a number? Like an if statement to check if the variables a number and if it is do ...
- 04-22-2007 #1Just Joined!
- Join Date
- Sep 2005
- Posts
- 99
checking if a variable is a number
Is there a way in bash to check if a variable is a number? Like an if statement to check if the variables a number and if it is do one thing if its not do another?
- 04-22-2007 #2Linux Enthusiast
- Join Date
- Aug 2006
- Posts
- 631
You can delete all the numbers of the variable and test if the string is empty.
Ifgives an empty string it is an number.Code:${variable//"[0-9]"}
I suggest you to read some stuff about bash programming, go here for the tutorials:
http://www.tldp.org/LDP/Bash-Beginne...tml/index.html
http://tldp.org/LDP/abs/html/
Regards
- 04-22-2007 #3Linux User
- Join Date
- Aug 2006
- Posts
- 458
simple checking:
Code:echo $var | awk '$0 !~ /[a-zA-Z]/ {print "A number"}'
- 04-22-2007 #4Linux Engineer
- Join Date
- Apr 2006
- Location
- Saint Paul, MN, USA / CentOS, Debian, Solaris, SuSE
- Posts
- 1,117
Hi.
Whatever you choose for a specific solution, it will probably involve regular expressions, so you need to decide what "a number" means to you in your problem context. Is it a simple integer? Signed? Decimal fraction? Exponential format? Double precision? Quad precision?
Do you need to diagnose faults, say perhaps with 2 decimal points in a candidate string?
That will determine what characters would be in the regular expression, as well as the complexity.
For example, The AWK Programming Language, has
for a pattern in awk that matches a line that consists only of numeric characters. Using grep perhaps in a shell script, you probably would useCode:/^[0-9]+$/
essentially the same thing except for the shell-isolating-quotes in place of the bounding slashes.Code:'^[0-9]+$'
The links from Franklin52 are useful, particularly Chapter 4 of the Beginner link ... cheers, drlWelcome - get the most out of the forum by reading forum basics and guidelines: click here.
90% of questions can be answered by using man pages, Quick Search, Advanced Search, Google search, Wikipedia.
We look forward to helping you with the challenge of the other 10%.
( Mn, 2.6.n, AMD-64 3000+, ASUS A8V Deluxe, 1 GB, SATA + IDE, Matrox G400 AGP )


Reply With Quote