在 Bash 中使用变量作为大小写模式

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

Using variable as case pattern in Bash

bashpattern-matchingswitch-statement

提问by siebz0r

I'm trying to write a Bash script that uses a variable as a pattern in a case statement. However I just cannot get it to work.

我正在尝试编写一个 Bash 脚本,该脚本在 case 语句中使用变量作为模式。但是我就是无法让它工作。

Case statement:

案例说明:

case "" in
    $test)
        echo "matched"
        ;;
    *)
        echo "didn't match"
        ;;
esac

I've tried this with assigning $testas aaa|bbb|ccc, (aaa|bbb|ccc), [aaa,bbb,ccc]and several other combinations. I also tried these as the pattern in the case statement: @($test), @($(echo $test)), $($test). Also no success.

我已经试过分配此$testaaa|bbb|ccc(aaa|bbb|ccc)[aaa,bbb,ccc]和其他几个组合。我还尝试将这些作为 case 语句中的模式:@($test), @($(echo $test)), $($test)。也没有成功。

EDIT

编辑

For clarity, I would like the variable to represent multiple patterns like this:

为清楚起见,我希望变量表示这样的多个模式:

case "" in
    aaa|bbb|ccc)
        echo "matched"
        ;;
    *)
        echo "didn't match"
        ;;
esac

回答by choroba

You can use the extgloboption:

您可以使用以下extglob选项:

#! /bin/bash

shopt -s extglob         # enables pattern lists like +(...|...)
test='+(aaa|bbb|ccc)'

for x in aaa bbb ccc ddd ; do
    echo -n "$x "
    case "$x" in
        $test) echo Matches.
        ;;
        *) echo Does not match.
    esac
done

回答by sampson-chen

(Updated): here's something a bit different, but I hope it works for what you need it for:

更新):这里有些不同,但我希望它可以满足您的需求:

#!/bin/bash

pattern1="aaa bbb ccc"
pattern2="hello world"
test=$(echo -e "$pattern1\n$pattern2" | grep -e )

case "$test" in
    "$pattern1")
        echo "matched - pattern1"
        ;;
    "$pattern2")
        echo "matched - pattern2"
        ;;
    *)
        echo "didn't match"
        ;;
esac

This makes use of grepto do the pattern matching for you, but still allows you to specify multiple pattern sets to be used in a case-statement structure.

这利用grep为您进行模式匹配,但仍允许您指定多个模式集以在 case 语句结构中使用。

For instance:

例如:

  • If either aaa, bbb, or cccis the first argument to the script, this will output matched - pattern1.
  • If either helloor worldis the first argument, this will output matched - pattern2.
  • Otherwise it will output didn't match.
  • 如果aaa, bbb, 或ccc是脚本的第一个参数,则将输出matched - pattern1.
  • 如果helloworld是第一个参数,这将输出matched - pattern2.
  • 否则它会输出didn't match.

回答by mliberi

using eval also works:

使用 eval 也有效:

eval 'case "" in

    '$test')
        echo "matched"
        ;;
    *)
        echo "did not match"
        ;;
esac'