Find the answer to your Linux question:
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 ...
  1. #1
    Just 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?

  2. #2
    Linux Enthusiast
    Join Date
    Aug 2006
    Posts
    631
    You can delete all the numbers of the variable and test if the string is empty.
    If
    Code:
    ${variable//"[0-9]"}
    gives an empty string it is an number.

    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

  3. #3
    Linux User
    Join Date
    Aug 2006
    Posts
    458
    simple checking:
    Code:
    echo $var | awk '$0 !~ /[a-zA-Z]/ {print "A number"}'

  4. #4
    drl
    drl is offline
    Linux Engineer drl's Avatar
    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
    Code:
    /^[0-9]+$/
    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 use
    Code:
    '^[0-9]+$'
    essentially the same thing except for the shell-isolating-quotes in place of the bounding slashes.

    The links from Franklin52 are useful, particularly Chapter 4 of the Beginner link ... cheers, drl
    Welcome - 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 )

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...