如何在 Bash 中进行不区分大小写的字符串比较?

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

How can I do case-insensitive string comparison in Bash?

bashshell

提问by viet

My script:

我的脚本:

echo "input yes or no"
read a
if [ $a = "yes" ] or [ $a = "Yes" ] or [ $a = "YES" ];
then
    command
else
    command
done

I have an idea that I will convert the answer (using the tr A-Z a-zcommand) first and after that compare with string... is that okay?

我有一个想法,我将首先转换答案(使用tr A-Z a-z命令),然后与字符串进行比较......可以吗?

回答by sat

You can use shopt -s nocasematch.

您可以使用shopt -s nocasematch.

Try this :

尝试这个 :

shopt -s nocasematch
echo "Input yes or no"
read a
if [[ $a == "yes" ]]
then
    echo "YES"
else
    echo "NO"
fi

From bash:

来自bash

nocasematch

If set, Bash matches patterns in a case-insensitive fashion when performing matching while executing case or [[ conditional commands.

nocasematch

如果设置,Bash 在执行 case 或 [[ 条件命令时执行匹配时以不区分大小写的方式匹配模式。

回答by stalet

Here is an example on how to do it without conversion in bash 4. You can use parameter expansion to inline change the value of the $avariable.

这是一个关于如何在 bash 4 中不进行转换的示例。您可以使用参数扩展来内联更改$a变量的值。

#!/bin/bash

echo "input yes or no"
read a
if [ ${a,,} = "yes" ];
then
    echo "test 1"
else
    echo "test 2"
fi

回答by Dummy00001

You can use the dialogtool available on most systems, which can display an interactive dialog in the console:

您可以使用dialog大多数系统上可用的工具,该工具可以在控制台中显示交互式对话框:

if dialog  --title example1 --backtitle example2 --yesno "Make a choice!" 7 60
then
    echo "YES"
else
    echo "NO"
fi

Bypasses the case-sensitivity of the user input completely.

完全绕过用户输入的区分大小写。

More examples.

更多例子。