Bash to exit on no reponse

The below bash does not seem to exit if the user response is n N no No . Is the synatax incorrect? Thank you :).

Bash

read -r -p "Is this correct? [y/N] " response
if [[ $response =~ ^([nN][oO)$ ]]
then
    echo "The files do not match"  && exit ;;
else
.... do something
fi

Hello cmccabe,

Could you please try following.

read -r -p "Is this correct? [yes/No] " response
if [[ $response =~ ([no]||[NO]||[No]||[nO]) ]]
then
    echo "The files do not match"
        exit
else
        echo ".... do something";
fi

It sees for string entered from users like No,nO,NO,no too.

Thanks,
R. Singh

1 Like

Thank you very much, works great :).

Use a case statement:

read -r -p "Is this correct? [yes/No] " response
case $response in
    [yY] | [yY][Ee][Ss] )
        do something
        ;;

     [nN] | [n|N][O|o] )
        echo "The files do not match"
        exit
        ;;
esac

Maybe the following would give you an example to work from:

#!/bin/bash
while [ 1 ]
do
	read -r -p "Is this correct? [y/N] " response
	if [[ $response =~ ^[nN][oO]?$ ]]
	then
		echo 'match'  && exit
	else
		echo 'no match'
	fi
done

The RE ^[nN][oO]?$ matches a one or two character string anchored at the start of the string ( ^ ) where the first character is a lowercase or uppercase n ( [nN] ), followed by zero or one ( ? ) lowercase or uppercase o ( [oO] ), and anchored to the end of the string ($) .

or more easily, declare response as a low-case variable: typeset -l response and you don't have to permute all the possible combinations...

1 Like