0

I am attempting to add regex validation to read -p, for example a domain name.

Current Code:

read -p "Do Something": dosomething
echo working on $dosomething

Thank you for the update as-per validating email, I trying to figure out if it is possible to apply regex validation at all to read -p.

Jhd33
  • 74
  • 5
  • Note that "using regex to validate that a string is an email address" is also an impossible task. See [this question](https://stackoverflow.com/questions/201323/how-to-validate-an-email-address-using-a-regular-expression), and especially [this answer](https://stackoverflow.com/a/202528). – Daniel Pryden Sep 26 '18 at 12:17

2 Answers2

1

Use a loop:

email=""
until [[ $email =~ $regex ]] ; do
    read -p 'Enter your email: ' email
done

The regex

(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])

shown at EmailRegex.com isn't bash compatible, unfortunately.

choroba
  • 231,213
  • 25
  • 204
  • 289
0

Short answer: sure, this is something that read could hypothetically do. But bash's implementation of read does not have this feature, and I don't know of any POSIX-compatible shell that does, and POSIX itself does not include such a feature, although it seems like the kind of thing that an implementation could add as an extension if desired. If you like the feature enough, consider submitting a patch to bash to add it!

It's easy enough to build validation using read: just use a loop to read a value, check to see if it is valid, and if not, try again. You can write this as a bash function if you feel the need to do this on a regular basis.

Daniel Pryden
  • 59,486
  • 16
  • 97
  • 135