OILS / spec / sh-func.test.sh View on Github | oilshell.org

150 lines, 89 significant
1
2#### Locals don't leak
3f() {
4 local f_var=f_var
5}
6f
7echo $f_var
8## stdout:
9
10#### Globals leak
11f() {
12 f_var=f_var
13}
14f
15echo $f_var
16## stdout: f_var
17
18#### Return statement
19f() {
20 echo one
21 return 42
22 echo two
23}
24f
25## stdout: one
26## status: 42
27
28#### Dynamic Scope
29f() {
30 echo $g_var
31}
32g() {
33 local g_var=g_var
34 f
35}
36g
37## stdout: g_var
38
39#### Dynamic Scope Mutation (wow this is bad)
40f() {
41 g_var=f_mutation
42}
43g() {
44 local g_var=g_var
45 echo "g_var=$g_var"
46 f
47 echo "g_var=$g_var"
48}
49g
50echo g_var=$g_var
51## STDOUT:
52g_var=g_var
53g_var=f_mutation
54g_var=
55## END
56
57#### Assign local separately
58f() {
59 local f
60 f='new-value'
61 echo "[$f]"
62}
63f
64## stdout: [new-value]
65## status: 0
66
67#### Assign a local and global on same line
68myglobal=
69f() {
70 local mylocal
71 mylocal=L myglobal=G
72 echo "[$mylocal $myglobal]"
73}
74f
75echo "[$mylocal $myglobal]"
76## stdout-json: "[L G]\n[ G]\n"
77## status: 0
78
79#### Return without args gives previous
80f() {
81 ( exit 42 )
82 return
83}
84f
85echo status=$?
86## STDOUT:
87status=42
88## END
89
90#### return "" (a lot of disagreement)
91f() {
92 echo f
93 return ""
94}
95
96f
97echo status=$?
98## STDOUT:
99f
100status=0
101## END
102## status: 0
103
104## OK dash status: 2
105## OK dash STDOUT:
106f
107## END
108
109## BUG mksh STDOUT:
110f
111status=1
112## END
113
114## BUG bash STDOUT:
115f
116status=2
117## END
118
119#### return $empty
120f() {
121 echo f
122 empty=
123 return $empty
124}
125
126f
127echo status=$?
128## STDOUT:
129f
130status=0
131## END
132
133#### Subshell function
134
135f() ( return 42; )
136# BUG: OSH raises invalid control flow! I think we should just allow 'return'
137# but maybe not 'break' etc.
138g() ( return 42 )
139# bash warns here but doesn't cause an error
140# g() ( break )
141
142f
143echo status=$?
144g
145echo status=$?
146
147## STDOUT:
148status=42
149status=42
150## END