1 |
#!/usr/bin/env bash |
2 |
|
3 |
#### Locals don't leak |
4 |
f() { |
5 |
local f_var=f_var |
6 |
} |
7 |
f |
8 |
echo $f_var |
9 |
## stdout: |
10 |
|
11 |
#### Globals leak |
12 |
f() { |
13 |
f_var=f_var |
14 |
} |
15 |
f |
16 |
echo $f_var |
17 |
## stdout: f_var |
18 |
|
19 |
#### Return statement |
20 |
f() { |
21 |
echo one |
22 |
return 42 |
23 |
echo two |
24 |
} |
25 |
f |
26 |
## stdout: one |
27 |
## status: 42 |
28 |
|
29 |
#### Dynamic Scope |
30 |
f() { |
31 |
echo $g_var |
32 |
} |
33 |
g() { |
34 |
local g_var=g_var |
35 |
f |
36 |
} |
37 |
g |
38 |
## stdout: g_var |
39 |
|
40 |
#### Dynamic Scope Mutation (wow this is bad) |
41 |
f() { |
42 |
g_var=f_mutation |
43 |
} |
44 |
g() { |
45 |
local g_var=g_var |
46 |
f |
47 |
echo "g: $g_var" |
48 |
} |
49 |
g |
50 |
## stdout: g: f_mutation |
51 |
|
52 |
#### Assign local separately |
53 |
f() { |
54 |
local f |
55 |
f='new-value' |
56 |
echo "[$f]" |
57 |
} |
58 |
f |
59 |
## stdout: [new-value] |
60 |
## status: 0 |
61 |
|
62 |
#### Assign a local and global on same line |
63 |
myglobal= |
64 |
f() { |
65 |
local mylocal |
66 |
mylocal=L myglobal=G |
67 |
echo "[$mylocal $myglobal]" |
68 |
} |
69 |
f |
70 |
echo "[$mylocal $myglobal]" |
71 |
## stdout-json: "[L G]\n[ G]\n" |
72 |
## status: 0 |
73 |
|
74 |
#### Return without args gives previous |
75 |
f() { |
76 |
( exit 42 ) |
77 |
return |
78 |
} |
79 |
f |
80 |
echo status=$? |
81 |
## STDOUT: |
82 |
status=42 |
83 |
## END |