Case insensitive regex in Bash
You can first convert the string into lowercase and check it. Then you don't need to touch nocasematch
at all. The content of the variable is left unmodified as well.
#
# NOTE: This requires Bash 4.0+ (bash 4.0 was released on 2009-02-20)
#
# use the ${var,,} syntax to convert to lowercase
#
while [[ ! ${yesno,,} =~ ^(y|n|yes|no)$ ]]; do
read -r -p "yes/no? " yesno
done
shopt
is good approach as you are able to retain originally entered value in variable yesno
.
You can just refactor your regex a bit:
#!/bin/bash
yesno="null"
# set nocasematch option
shopt -s nocasematch
while [[ ! ${yesno} =~ ^([yn]|yes|no)?$ ]]; do
read -r -p "Enter a yes/no value: " yesno
done
# unset nocasematch option
shopt -u nocasematch
# examine your variable
declare -p yesno