Bash – Check if string contains only numeric

To check if string contains only numeric digits in Bash scripting, you can use regular expression ^[0-9]+$. In this expression ^ matches starting of the string, [0-9]+ matches one or more digits, and $ matches end of the string.

Examples

In the following script, we take a string in str which contains only numeric digits. We shall programmatically check if string str contains only digits using regular expression.

example.sh

#!/bin/bash
 
str="123454321"

if [[ $str =~ ^[0-9]+$ ]]; then
  echo "String contains only numeric digits."
else
  echo "String does not contain only numeric digits."
fi

Output

sh-3.2# ./example.sh 
String contains only numeric digits.

Now let us take a value in the string str such that it not only contains digits, but also some alphabets.

example.sh

#!/bin/bash
 
str="123454321ABC"

if [[ $str =~ ^[0-9]+$ ]]; then
  echo "String contains only numeric digits."
else
  echo "String does not contain only numeric digits."
fi

Output

sh-3.2# ./example.sh 
String does not contain only numeric digits.

References

Bash If Else

ADVERTISEMENT

Conclusion

In this Bash Tutorial, we learned how to check if string contains only numeric digits using regular expression.