0
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.

nobody user
  • 131
  • 5
  • Can you copy the explanation from `man bash` and explain what's not clear about it? – that other guy Dec 08 '17 at 01:35
  • Are you sure you understand the "[ operand"? I ask because `[` is not an operator, and it seems very odd to use the phrase "[ operand". Also, this script doesn't use `[`. It uses `[[`, which is a very different thing. – William Pursell Dec 08 '17 at 01:58
  • @William Pursell Oh I thought the `[` and `[[` are same thanks for the explanation by the way. – nobody user Dec 08 '17 at 02:03

1 Answers1

2
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.

iBug
  • 30,581
  • 7
  • 64
  • 105
  • 1
    I use this idiom extensively in my scripts, but I've found it's much simpler to use `if [[ "${response^^}" =~ ^Y(ES)?$ ]]`. The `^^` is a bashism that converts the string to upper case, which makes it a whole lot easier to write a regex for. – Mike Holt Dec 08 '17 at 01:37
  • @MikeHolt Freaking useful! Thank you for that idea about `^^`. – iBug Dec 08 '17 at 01:38
  • @iBug yes I want to do that but it says wait for 3 min ;( – nobody user Dec 08 '17 at 01:44
  • @iBug Could you explain what the `+` near the end does, please? – leetbacoon Jul 15 '19 at 17:49
  • 1
    @leetbacoon RegEx `+` means "repeat one or more times" and is equivalent to `{1,}`. – iBug Jul 15 '19 at 17:51
  • @iBug Thanks! Do you know about the `?` in Mike's answer? – leetbacoon Jul 15 '19 at 17:54
  • 1
    @leetbacoon I recommend you to take a look at [this post](https://stackoverflow.com/q/22937618/5958455) and maybe bookmark it for further references. – iBug Jul 15 '19 at 18:13