Reputation: 151
read -r -p "Are you sure? [y/N] " response
if [[ "$response" =~ ^([yY][eE][sS]|[yY])+$ ]]
then
do_something
else
do_something_else
fi
I saw this script on a stack overflow website I used the following script because I couldn't write one myself because it threw errors. I know this script will wait for user input such as y/n but I would like detailed explanation about how this script works like what does =~
do and what does ^([yY][eE][sS]|[yY])+$ ]]
do.
Upvotes: 0
Views: 68
Reputation: 37227
if [[ "$response" =~ ^([yY][eE][sS]|[yY])+$ ]]
The [[ ]]
is a bashism testing statement, similar to [ ]
but with a few differences. More detail is available in man bash
.
The =~
does RegEx matching, and
^([yY][eE][sS]|[yY])+$
is a regular expression, standing for One or more combinations of y
and yes
, case-insensitive.
It actually tests if the user's input is y
, Yes
, yES
, YyyY
or YyyYYesyesyes
(or anything else that matches the given RegEx).
From man 1 bash
:
An additional binary operator, =~, is available, with the same precedence as == and !=. When it is used, the string to the right of the operator is considered an extended regular expression and matched accordingly (as in
regex(3)
).
[[ expression ]]
Return a status of 0 or 1 depending on the evaluation of the conditional expression expression.
Upvotes: 2