1
2 #### try builtin
3 shopt --set errexit strict_errexit
4
5 myproc() {
6 echo hi
7 false
8 echo bye
9 }
10
11 case $SH in
12 (*osh)
13 # new semantics: the function aborts at 'false', the 'catch' builtin exits
14 # with code 1, and we echo 'failed'
15 try myproc || echo "failed"
16 ;;
17 (*)
18 myproc || echo "failed"
19 ;;
20 esac
21
22 ## STDOUT:
23 hi
24 failed
25 ## END
26 ## N-I dash/bash/mksh/ash STDOUT:
27 hi
28 bye
29 ## END
30
31 #### try with !
32 shopt -s oil:all || true
33
34 deploy() {
35 echo 'one'
36 false
37 echo 'two'
38 }
39
40 #if ! deploy; then
41 # echo 'failed'
42 #fi
43
44 if ! try deploy; then
45 echo 'failed'
46 fi
47 echo done
48
49 ## STDOUT:
50 one
51 failed
52 done
53 ## END
54
55 #### try -allow-status-01 with external command
56
57 set -o errexit
58
59 echo hi > file.txt
60
61 if try --allow-status-01 -- grep pat file.txt; then
62 echo 'match'
63 else
64 echo 'no match'
65 fi
66
67 if try --allow-status-01 -- grep pat BAD; then
68 echo 'match'
69 else
70 echo 'no match'
71 fi
72
73 echo DONE
74 ## status: 2
75 ## STDOUT:
76 no match
77 ## END
78
79 #### try -allow-status-01 with function
80
81 set -o errexit
82
83 echo hi > file.txt
84
85 myproc() {
86 echo ---
87 grep pat BAD # exits with code 2
88 #grep pat file.txt
89 echo ---
90 }
91
92 #myproc
93
94 if try --allow-status-01 -- myproc; then
95 echo 'match'
96 else
97 echo 'no match'
98 fi
99
100 ## status: 2
101 ## STDOUT:
102 ---
103 ## END
104
105 #### try syntax error
106 set -o errexit
107
108 # Irony: we can't fail that hard here because errexit is disabled before
109 # we enable it.
110 # TODO: We could special case this perhaps
111
112 if try; then
113 echo hi
114 else
115 echo fail
116 fi
117
118 ## status: 2
119 ## STDOUT:
120 ## END
121
122 #### try --assign
123 set -o errexit
124
125 myproc() {
126 return 42
127 }
128
129 try --assign st -- myproc
130 echo st=$st
131
132 # colon
133 try --assign :st -- myproc
134 echo st=$st
135
136
137 ## STDOUT:
138 st=42
139 st=42
140 ## END