3

Strange enough, [[ 111-11-1111 =~ "[0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]" ]] just yield success on command line.

But this script cannot yield the same when I bash re.sh 111-11-1111

#!/bin/bash
# re.sh

input=$1


if [[ "$input" =~ "[0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]" ]]
#                 ^ NOTE: Quoting not necessary, as of version 3.2 of Bash.
# NNN-NN-NNNN (where each N is a digit).
then
  echo "Social Security number."
  # Process SSN.
else
  echo "Not a Social Security number!"
  # Or, ask for corrected input.
fi

why?

Hao
  • 6,291
  • 9
  • 39
  • 88
  • 3
    Possible duplicate of [bash regex with quotes?](http://stackoverflow.com/questions/218156/bash-regex-with-quotes) – Snild Dolkow Apr 16 '16 at 14:42
  • 2
    I am using bash 4.3 and it only works when I leave out the second pair of quotes in the if: `if [[ "$input" =~ [0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9] ]]` . `bash -x re.sh` reveals some strange things going with qoutes present. – Lars Fischer Apr 16 '16 at 14:42

1 Answers1

1

As others have mentioned, you should remove the quotes on the regular expression if you're using bash 3.2 or higher. Also though, here's a shorter expression:

if [[ $input =~ ^[0-9]{3}-[0-9]{2}-[0-9]{4}$ ]]
drewyupdrew
  • 1,549
  • 1
  • 11
  • 16