Home > Mobile >  Loop a user input until it passes validation
Loop a user input until it passes validation

Time:09-15

I have the following in a bash script:-

#!/bin/bash

re="/(\W|^)php[5-9]{1}.[0-9]{1}-fpm.sock(\W|$)/gm"
while ! [[ "${socket}" =~ ${re} ]] 
do
    echo "enter socket string:"
    read socket
done

A valid $socket string from the user would equal php8.1-fpm.sock using the regex we're testing for. What actually happens is, the loop continues with a user unable to break out of it despite a valid string?

I should be able to use my $socket variable in the script following a successful validation. What am I missing?

Edit: Stuff I've tried:- re="/php[5-9]{1}.[0-9]{1}-fpm.sock/" omitting (\W)

CodePudding user response:

This could be done more correctly for the match, using standard globbing pattern matching of case in, with POSIX-shell grammar only.

#!/bin/sh

while case $socket in *php[5-9].[0-9]-fpm.sock) false ;; esac; do
  printf 'Enter socket string: '
  read -r socket
done

It could even test the socket is really an actual socket by testing -S:

#!/bin/sh

while case $socket in *php[5-9].[0-9]-fpm.sock) ! [ -S "$socket" ] ;; esac; do
  printf 'Enter socket string: '
  read -r socket
done

See man test:

  -S FILE
         FILE exists and is a socket
  • Related