当nocasematch关闭时,为什么case语句区分大小写?

时间:2012-05-22 02:26:03

标签: bash pattern-matching

鉴于以下内容:

$ echo $BASH_VERSION
4.2.10(1)-release

$ shopt | fgrep case
nocaseglob      off
nocasematch     off

$ case A in [a-z]) echo TRUE;; esac
TRUE

我希望大写字母 A 应该匹配 [a-z] 的小写字符类,但确实如此。为什么这场比赛没有失败?

2 个答案:

答案 0 :(得分:7)

您不能以这种方式可靠地使用短划线。如果我不使用短划线,它按预期工作:

$ bash --version
GNU bash, version 4.2.10(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
$ shopt -s nocasematch
$ case A in [abc]) echo TRUE;; esac
TRUE
$ shopt -u nocasematch
$ case A in [abc]) echo TRUE;; esac
$ 

使用破折号,无论nocasematch的设置如何,它都会打印为TRUE。

Bash在这里进行模式匹配。查看this section of the reference manual,其中使用连字符MIGHT将[a-z]解释为[A-Za-z]!它告诉您如何获得传统解释(将LC_COLLATE或LC_ALL设置为C)。基本上,您的默认语言环境是按字典顺序排序。参考手册很好地解释了事情。

<强>附录

好的,我有你的成绩单。

$ shopt -u nocasematch
$ case A in [a-z]) echo TRUE;; esac
TRUE
$ shopt -s nocasematch
$ case A in [a-z]) echo TRUE;; esac
TRUE
$ LC_ALL=C
$ shopt -u nocasematch
$ case A in [a-z]) echo TRUE;; esac
$ shopt -s nocasematch
$ case A in [a-z]) echo TRUE;; esac
TRUE

答案 1 :(得分:7)

它与您的区域设置有关。具体来说,整理顺序是一个不区分大小写的顺序。

例如,将LC_COLLATE设置为en_AU.utf8(系统上的默认值),您可以看到它包含小写和大写:

pax> case A in [a-b]) echo TRUE;; esac
TRUE
pax> _

但是,如果你摆脱范围说明符,它按预期工作:

pax> case A in [ab]) echo TRUE;; esac
pax> _

这是因为第一个意味着between a and b inclusive,对于该整理顺序,包括A。对于后者,仅指ab,而不是受整理顺序影响的范围。

如果您将整理顺序设置为区分大小写的顺序,则它会按预期运行:

pax> export LC_COLLATE="C"
pax> case A in [a-b]) echo TRUE;; esac
pax> 

如果您只想在不影响其他任何事情的情况下将其作为一次性操作执行,则可以在子shell中执行此操作:

( export LC_COLLATE="C" ; case A in [a-b]) echo TRUE;; esac )
相关问题