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

[[ $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:].


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

Tags:

Bash