Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string only contains digits/numerical characters

Tags:

How can I check if MyVar contains only digits with an if statement with BASH. By digits I am referring to 0-9.

ie:

if [[ $MyVar does contain digits ]]  <-- How can I check if MyVar is just contains numbers
then
 do some maths with $MyVar
else
 do a different thing
fi
like image 679
3kstc Avatar asked Aug 19 '15 23:08

3kstc


People also ask

How do you check if a string is all digits in Java?

To check if String contains only digits in Java, call matches() method on the string object and pass the regular expression "[0-9]+" that matches only if the characters in the given string are digits.


2 Answers

Here it is:

#!/bin/bash
if [[ $1 =~ ^[0-9]+$ ]]
then
    echo "ok"
else
    echo "no"
fi

It prints ok if the first argument contains only digits and no otherwise. You could call it with: ./yourFileName.sh inputValue

like image 63
giliev Avatar answered Sep 19 '22 15:09

giliev


[[ $myvar =~ [^[:digit:]] ]] || echo All Digits

Or, if you like the if-then form:

if [[ $myvar =~ [^[:digit:]] ]]
then
    echo Has some nondigits
else
    echo all digits
fi

In olden times, we would have used [0-9]. Such forms are not unicode safe. The modern unicode-safe replacement is [:digit:].

like image 32
John1024 Avatar answered Sep 22 '22 15:09

John1024