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.

  • i think that count is always a string – jsotola Mar 17 at 7:21
  • @jsotola why??? – BlackCrystal Mar 17 at 7:24
  • You might be better off sticking to POSIX in that case (albeit at the expense of using a pipe). It seems more readable: echo "${count// /}" | grep -Eq "^[0-9]+$" && echo 0 || echo 1 even though not everybody (stackoverflow.com/questions/17420994/bash-regex-match-string) agrees. – Cbhihe Mar 17 at 12:02
  • 1
    @BlackCrystal A variable's value is always a string. If it is a number, such as 123, then it is a string of digits. Note too that -123 is an integer, but not a string of digits as it also contains a dash, and that 12.3e-23 and 0.123 are numbers, but not strings of digits exclusively. – Kusalananda Mar 17 at 12:28

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).
  • 2
    If it contains digits (and maybe some spaces) it's printed out with multiple adjacent spaces reduced to a single space, and leading/trailing space removed. – roaima Mar 17 at 7:19
  • 1
    why couldn't it be just if ! [[ $count =~ ^[0-9\ ]+$ ]] ...? – mosvy Mar 17 at 7:23
  • 1
    @BlackCrystal It is. Instead of removing the spaces and comparing against digits, the unmodified string is compared against digits and spaces. – Kusalananda Mar 17 at 8:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.