Sample Header Ad - 728x90

Using Bash "=~" operator with WHILE instead of UNTIL loop

0 votes
1 answer
687 views
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-Z0-9-]){0,61}[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.
Asked by phunsoft (178 rep)
Feb 24, 2023, 04:01 PM
Last activity: Feb 24, 2023, 05:07 PM