简体   繁体   中英

How does this Bash script work?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM