Skip to main content

Syntax for checking if variable contains digits only in bash [Resolved]

I was reviewing some old scripts on my machines and I saw this if expression and I have no idea what it is doing. Can someone explain it?

if ! [[ "${count// /}" =~ ^[0-9]+$ ]]
  echo 1
  echo $count

value of count is sometimes string and sometimes an integer.

Question Credit: BlackCrystal
Question Reference
Asked March 17, 2019
Posted Under: Unix Linux
1 Answers

Let's break it down to individual components

  1. The syntax "${count// /}" is a parameter expansion syntax to replace all spaces in the content of variable with an empty string. e.g. 2 1 becomes just 21
  2. The part =~ ^[0-9]+$ runs the bash regex operation match the string on the left hand side to a set of digits only.
  3. The part ! [[..]] negates the whole operation, which means the condition becomes true only if the content of count is not a string of digits.
  4. On the positive condition of the if you echo out the numeric value of 1 and on failure of if, it returns the actual value of count without the stripping of spaces done in 1).

credit: Kusalananda
Answered March 17, 2019
Your Answer