1 #!/usr/bin/env bash
2 #
3 # Test the case statement
4
5 #### Case statement
6 case a in
7 a) echo A ;;
8 *) echo star ;;
9 esac
10 ## stdout: A
11
12 #### Case statement with ;;&
13 # ;;& keeps testing conditions
14 # NOTE: ;& and ;;& are bash 4 only, no on Mac
15 case a in
16 a) echo A ;;&
17 *) echo star ;;&
18 *) echo star2 ;;
19 esac
20 ## status: 0
21 ## stdout-json: "A\nstar\nstar2\n"
22 ## N-I dash stdout-json: ""
23 ## N-I dash status: 2
24
25 #### Case statement with ;&
26 # ;& ignores the next condition. Why would that be useful?
27 case a in
28 a) echo A ;&
29 XX) echo two ;&
30 YY) echo three ;;
31 esac
32 ## status: 0
33 ## stdout-json: "A\ntwo\nthree\n"
34 ## N-I dash stdout-json: ""
35 ## N-I dash status: 2
36
37 #### Case with empty condition
38 case $empty in
39 ''|foo) echo match ;;
40 *) echo no ;;
41 esac
42 ## stdout: match
43
44 #### Match a literal with a glob character
45 x='*.py'
46 case "$x" in
47 '*.py') echo match ;;
48 esac
49 ## stdout: match
50
51 #### Match a literal with a glob character with a dynamic pattern
52 x='b.py'
53 pat='[ab].py'
54 case "$x" in
55 $pat) echo match ;;
56 esac
57 ## stdout: match
58
59 #### Quoted literal in glob pattern
60 x='[ab].py'
61 pat='[ab].py'
62 case "$x" in
63 "$pat") echo match ;;
64 esac
65 ## stdout: match
66
67 #### Multiple Patterns Match
68 x=foo
69 result='-'
70 case "$x" in
71 f*|*o) result="$result X"
72 esac
73 echo $result
74 ## stdout: - X
75
76 #### Match one unicode char
77
78 # These two code points form a single character.
79 two_code_points="__$(echo $'\u0061\u0300')__"
80
81 # U+0061 is A, and U+0300 is an accent.
82 #
83 # (Example taken from # https://blog.golang.org/strings)
84 #
85 # However ? in bash/zsh only counts CODE POINTS. They do NOT take into account
86 # this case.
87
88 for s in '__a__' '__μ__' "$two_code_points"; do
89 case $s in
90 __?__)
91 echo yes
92 ;;
93 *)
94 echo no
95 esac
96 done
97 ## STDOUT:
98 yes
99 yes
100 no
101 ## END
102 ## BUG dash/mksh STDOUT:
103 yes
104 no
105 no
106 ## END
107
108 #### case with single byte LC_ALL=C
109
110 LC_ALL=C
111
112 c=$(printf \\377)
113
114 # OSH prints -1 here
115 #echo "${#c}"
116
117 case $c in
118 '') echo a ;;
119 "$c") echo b ;;
120 esac
121
122 ## STDOUT:
123 b
124 ## END