0

I would like someone to clarify this because I don't understand it. Here is a sample code, that tests an argument if it is numeric or not (integer)

#/bin/env bash
pattern="^[+|-]?[0-9]+$"
[[ "$1" =~ "$pattern" ]] && echo "1:number" || echo "1:NOT number"
[[ "$1" =~ $pattern ]] && echo "1:number" || echo "1:NOT number"

it is advisable to quote always the variables, but here, if you make the test with this simple script with various inputs, you will see that if you enter a number, the quoted pattern variable returns an erroneous result (first test) Why is that? thanks in advance for anyone who will take the trouble to explain this to me. Finally, sorry if that is already answered but I haven't found that particular one.

Savvas
  • 1
  • You are inside `[[ ... ]]`, so the usual quoting rules don't apply. There is a different set of quoting rules in this case. and for pattern matching, your quotes inhibit the interpretation of the special regex characters. – user1934428 Mar 04 '21 at 09:16

1 Answers1

0

It's normally advised to quote all variables. But [[ ]] is a special operator, it parses its contents differently.

You don't need to quote variables inside double square brackets, because it doesn't do word splitting or filename expansion. But there's no harm in quoting most variables.

However, the pattern operand to =~ is treated very specially. Any part of it that's quoted is treated as a literal, not a regular expression pattern. So when you write "$pattern" it no longer does a regular expression match, it just searches for the actual characters in $pattern in $1.

Barmar
  • 741,623
  • 53
  • 500
  • 612