shell脚本中case条件控制语句的一个bug分析
在shell脚本中,发现case语句的一个问题。
就是指定小写字母[a-z]和大写字母[a-z]的这种方法不管用了。
出现如下情况:
[root@station1 ~]# cat case.sh
#!/bin/bash
while :
do
echo -n "input a letter: "
read var
case "$var" in
[a-z]) echo "lowercase letter";;
[a-z]) echo "uppercase letter";;
[0-9]) echo "digit";;
*) echo "punctuation, whitespace, or other";;
esac
done
[root@station1 ~]# bash case.sh
input a letter: a
lowercase letter
input a letter: a
lowercase letter
input a letter: 2
digit
input a letter: 0
digit
input a letter: b
lowercase letter
input a letter: y
lowercase letter
input a letter: ^c
[root@station1 ~]#
可以看到当输入大小写字母都会输出“lowercase letter”
就当我疑惑不解的时候,奇迹发生了。。。。
[root@station1 ~]# bash case.sh
input a letter: z
uppercase letter
input a letter:
当输入大写z的时候,终于出现了我们想要的结果:uppercase letter
后来在man bash文档中也没有关于"-"代表范围的说明,值说想匹配"-",就把"-"放到[]中最前面或者最后面。
case word in [ [(] pattern [ | pattern ] ... ) list ;; ] ... esac
a case command first expands word, and tries to match it against each pattern in turn, using the same matching rules as for pathname
expansion (see pathname expansion below). the word is expanded using tilde expansion, parameter and variable expansion, arithmetic sub-
stitution, command substitution, process substitution and quote removal. each pattern examined is expanded using tilde expansion, param-
eter and variable expansion, arithmetic substitution, command substitution, and process substitution. if the shell option nocasematch is
enabled, the match is performed without regard to the case of alphabetic characters. when a match is found, the corresponding list is
executed. if the ;; operator is used, no subsequent matches are attempted after the first pattern match. using ;& in place of ;; causes
execution to continue with the list associated with the next set of patterns. using ;;& in place of ;; causes the shell to test the next
pattern list in the statement, if any, and execute any associated list on a successful match. the exit status is zero if no pattern
matches. otherwise, it is the exit status of the last command executed in list.
再看下面这段代码:
[root@station1 ~]# cat case.sh
#!/bin/bash
while :
do
echo -n "input a letter: "
read var
case "$var" in
[a-c]) echo "lowercase letter";;
[a-z]) echo "uppercase letter";;
[0-9]) echo "digit";;
*) echo "punctuation, whitespace, or other";;
esac
done
[root@station1 ~]# bash case.sh
input a letter: a
lowercase letter
input a letter: b
lowercase letter
input a letter: c
lowercase letter
input a letter: d
uppercase letter
input a letter: e
uppercase letter
input a letter: ^c
[root@station1 ~]#
可以看出来它的编码方式是:aabbccddee...yyzz
所以才会出现这种情况。这也算是一个小bug吧,如果想真的想达到我们想要的结果,可以用posix的[:upper:]。
个人想法:有时候出现这种情况也不是个坏事,或许还可以利用这个bug去做点事。
上一篇: 复制粘贴功能的Python程序