bash 正则表达式电子邮件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32291127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:30:59  来源:igfitidea点击:

bash regex email

regexbashvalidationemailinteractive

提问by FedeKrum

I am traying to interactively ask in bash for an email address till it gets a valid one. Here is the code.

我正在尝试以交互方式在 bash 中询问一个电子邮件地址,直到它得到一个有效的地址。这是代码。

#!/bin/bash
email=""
email_status=[ "$email" =~ ^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$ ]
while [ $email_status ]
do
    read -p "Enter admin email: " email
    echo
    if [[ "$email" =~ ^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$ ]]
    then
        echo "Email address $email is valid."
    else
        echo "Email address $email is invalid."
    fi
done

I don't get why is not working.

我不明白为什么不起作用。

回答by Eric Renouf

The main problem is with the part where you seem to be setting up the conditions for the initial condition for the whileloop. We can simplify the whole loop by just exiting the loop on the desired condition like:

主要问题在于您似乎在为while循环的初始条件设置条件的部分。我们可以通过在所需条件下退出循环来简化整个循环,例如:

#!/bin/bash

while true
do
    read -p "Enter admin email: " email
    echo
    if [[ "$email" =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$ ]]
    then
        echo "Email address $email is valid."
        break
    else
        echo "Email address $email is invalid."
    fi
done

which I also modified to accept lower case characters.

我还修改为接受小写字符。

So why did the initial version you have not work? For starters, you aren't actually executing the command you want. The command would be parsed with the =assignment happening first, like you're assigning a local shell variable for the rest of the command to execute. So in this case you're assigning [to email_status, then trying to execute "$email" =~ ^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$ ]which isn't a real command.

那么为什么你的初始版本不起作用呢?对于初学者,您实际上并没有执行您想要的命令。该命令将在=分配首先发生的情况下进行解析,就像您正在为命令的其余部分分配一个本地 shell 变量以执行。因此,在这种情况下,您将分配[email_status,然后尝试执行"$email" =~ ^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$ ]这不是真正的命令。

Even if it were, your assignment still wouldn't work, because what you would actually have been wanting (aside from using [[so you can use the regex syntax) is to do that test, then store the exit code in exit_statuslike:

即使是这样,您的分配仍然不起作用,因为您实际上想要的(除了使用[[以便您可以使用正则表达式语法)是进行该测试,然后将退出代码存储为exit_status

[[ "$email" =~ ^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$ ]]
email_status=$?

and then make sure you update email_status within your loop, which your initial version did not do.

然后确保在循环中更新 email_status,这是您的初始版本没有做到的。