0

Bash has the =~ regular expression matching operator. Here is an example of using it:

#!/bin/bash

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

For negation, all the examples I have seen rely on an else clause. For situations where I am only interested in negative matches, is there a better way that making a non-functional if clause?

For example, if I only cared about the case where the above input is not a Not a Social Security number, what is the right way to go about this?

  • If you're expecting $input to be only a SSN, consider anchoring the regex -- ^[0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]$; otherwise input such as a555-44-99991 would match. – Jeff Schaller Oct 24 '18 at 1:11
  • @JeffSchaller SSN's are only from the stock example. I'm not using SSN's. – MountainX Oct 24 '18 at 1:36
3

You can negate at the top level:

if ! [[ …
  • I guess implementing !~ was too hard to disambituate from history expansion. – glenn jackman Oct 24 '18 at 3:50

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.