string bash字符串与多个正确值进行比较

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21157435/
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-09 02:12:27  来源:igfitidea点击:

bash string compare to multiple correct values

stringbashcomparisoncompare

提问by eagle00789

i have the following piece of bashscript:

我有以下一段 bashscript:

function get_cms {
    echo "input cms name"
    read cms
    cms=${cms,,}
    if [ "$cms" != "wordpress" && "$cms" != "meganto" && "$cms" != "typo3" ]; then
        get_cms
    fi
}

But no matter what i input (correct and incorrect values) it never calls the function again, because I only want to allow 1 of those 3 inputs. I have tried it with || with [ var != value ] or [ var != value1 ] or [ var != value1 ]but nothing works. Can someone point me in the right direction?

但是无论我输入什么(正确和不正确的值),它都不会再次调用该函数,因为我只想允许这 3 个输入中的 1 个。我用 || 试过了 与[ var != value ] or [ var != value1 ] or [ var != value1 ]但没有作品。有人可以指出我正确的方向吗?

采纳答案by devnull

Instead of saying:

而不是说:

if [ "$cms" != "wordpress" && "$cms" != "meganto" && "$cms" != "typo3" ]; then

say:

说:

if [[ "$cms" != "wordpress" && "$cms" != "meganto" && "$cms" != "typo3" ]]; then

You might also want to refer to Conditional Constructs.

您可能还想参考Conditional Constructs

回答by Edgar Grill

If the main intent is to check whether the supplied value is not found in a list, maybe you can use the extended regular expression matching built in BASH via the "equal tilde" operator (see also this answer):

如果主要目的是检查是否在列表中找不到提供的值,也许您可​​以通过“等号”运算符使用 BASH 中内置的扩展正则表达式匹配(另请参阅此答案):

if ! [[ "$cms" =~ ^(wordpress|meganto|typo3)$ ]]; then get_cms ; fi

Have a nice day

祝你今天过得愉快

回答by Alfe

Maybe you should better use a casefor such lists:

也许您应该更好地将 acase用于此类列表:

case "$cms" in
  wordpress|meganto|typo3)
    do_your_else_case
    ;;
  *)
    do_your_then_case
    ;;
esac

I think for long such lists this is better readable.

我认为长期这样的列表这是更好的可读性。

If you still prefer the ifyou can do it with single brackets in two ways:

如果你仍然喜欢if你可以通过两种方式用单括号做到这一点:

if [ "$cms" != wordpress -a "$cms" != meganto -a "$cms" != typo3 ]; then

or

或者

if [ "$cms" != wordpress ] && [ "$cms" != meganto ] && [ "$cms" != typo3 ]; then

回答by Renich

Here's my solution

这是我的解决方案

if [[ "${cms}" != +(wordpress|magento|typo3) ]]; then