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

时间:2016-06-17 10:35:53

标签: bash shell

我的剧本:

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

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

3 个答案:

答案 0 :(得分:6)

您可以使用shopt -s nocasematch

试试这个:

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

来自bash

  

nocasematch

     

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

答案 1 :(得分:4)

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

#!/bin/bash

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

答案 2 :(得分:2)

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

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

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

More examples.

相关问题