I'm writing some shell script which asks the user for a domain name. I'd like to prompt the user for input in a loop, and write an error message, if the input is not a valid domain name.
Basically, the code shall look like this:
#!/bin/bash
read -p "Enter domain name: " DOMAIN_NAME
while [[ testing for valid domain name goes here ]]
do
echo ''
echo 'You entered an invalid domain name. Please re-enter.'
echo '... more error message data ....'
echo ''
read -p "Enter domain name: " DOMAIN_NAME
done
echo "You entered domain name: $DOMAIN_NAME"
I've found some examples that show how the "=~" operator can be used to test against a reqular expression. However, the examples all show UNTIL
loops. Using the regex from the answer to question Check valid (sub)domain with regex in bash, an example is:
# !/bin/bash
until [[ "$DOMAIN_NAME" =~ ^(a-zA-Z0-9+[a-zA-Z]{2,5}$ ]]
do
read -p "Enter domain name: " DOMAIN_NAME
done
echo "You entered domain name: $DOMAIN_NAME"
While this works, it is not straitforward to write an additional error message in case the user entered invalid data. Such a message would have to be written inside the loop, before the read
, but not on first iteration.
For this reason I'd rather write the loop as a while
loop as shown above. I'm unable to find how I can negate the test expresssion, which is needed when rewriting the until
loop as a while
loop.
until ! [[ $foo =~ bar ]]
– jesse_b Feb 24 '23 at 16:02[^a-z]
which matches any character except from a-z, I was blinded and searched for the negation of the regular expression. Thanks. – phunsoft Feb 24 '23 at 18:30