bash 如果字符串包含 in case 语句

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

If string contains in case statement

stringbashshellswitch-statementsubstring

提问by Charabon

I'm looking to provide a case statement based on whether a substring is within a filename.

我希望提供一个基于子字符串是否在文件名中的 case 语句。

Example Input

示例输入

mysql_dumps/tpmysqldump-tps_dev_russell_development-information_schema-2014-03-26.sql

mysql_dumps/tpmysqldump-tps_dev_russell_development-information_schema-2014-03-26.sql

Code

代码

    case $DUMPFILE in
         *"tpdata"*)
             database="tpdata";;
         *"tpmrbs"*)
             database="tpmrbs";;
         *"information_schema"*)
             database="information_schema";;
         *"performance_schema"*)
             database="performance_schema";;
         *)
             echo "INVALID FILE";;
    esac

回答by slu

How do you initialize $DUMPFILE? If I run the following, the output is information_schema, which is what I expected...

你如何初始化 $DUMPFILE?如果我运行以下命令,输出为information_schema,这正是我所期望的......

#!/bin/bash
DUMPFILE=mysql_dumps/tpmysqldump-tps_dev_russell_development-information_schema-2014-03-26.sql
case $DUMPFILE in
    *"tpdata"*)
        database="tpdata";;
    *"tpmrbs"*)
        database="tpmrbs";;
    *"information_schema"*)
        database="information_schema";;
    *"performance_schema"*)
        database="performance_schema";;
    *)
        echo "INVALID FILE";;
esac
echo $database