1 |
#!/bin/bash |
2 |
# |
3 |
# Var refs are done with ${!a} and local/declare -n. |
4 |
# |
5 |
# http://stackoverflow.com/questions/16461656/bash-how-to-pass-array-as-an-argument-to-a-function |
6 |
|
7 |
### pass array by reference |
8 |
show_value() { |
9 |
local -n array=$1 |
10 |
local idx=$2 |
11 |
echo "${array[$idx]}" |
12 |
} |
13 |
shadock=(ga bu zo meu) |
14 |
show_value shadock 2 |
15 |
# stdout: zo |
16 |
|
17 |
### pass assoc array by reference |
18 |
show_value() { |
19 |
local -n array=$1 |
20 |
local idx=$2 |
21 |
echo "${array[$idx]}" |
22 |
} |
23 |
days=([monday]=eggs [tuesday]=bread [sunday]=jam) |
24 |
show_value days sunday |
25 |
# stdout: jam |
26 |
# BUG mksh stdout: [monday]=eggs |
27 |
# mksh note: it coerces "days" to 0? Horrible. |
28 |
|
29 |
### pass local array by reference, relying on DYNAMIC SCOPING |
30 |
show_value() { |
31 |
local -n array=$1 |
32 |
local idx=$2 |
33 |
echo "${array[$idx]}" |
34 |
} |
35 |
caller() { |
36 |
local shadock=(ga bu zo meu) |
37 |
show_value shadock 2 |
38 |
} |
39 |
caller |
40 |
# stdout: zo |
41 |
# mksh appears not to hav elocal arrays! |
42 |
# BUG mksh stdout-json: "" |
43 |
# BUG mksh status: 1 |
44 |
|
45 |
### Var ref with ${!a} |
46 |
a=b |
47 |
b=c |
48 |
echo ref ${!a} |
49 |
# Woah mksh has a completely different behavior -- var name, not var ref. |
50 |
# stdout: ref c |
51 |
# BUG mksh stdout: ref a |
52 |
# N-I dash/zsh stdout-json: "" |
53 |
|
54 |
### Bad var ref with ${!a} |
55 |
#set -o nounset |
56 |
a='bad var name' |
57 |
echo ref ${!a} |
58 |
# Woah even dash implements this! |
59 |
# stdout-json: "ref\n" |
60 |
# BUG mksh stdout: ref a |
61 |
# N-I dash/zsh stdout-json: "" |
62 |
|
63 |
### Nested ${} |
64 |
bar=ZZ |
65 |
echo ${foo:-${bar}} |
66 |
# stdout: ZZ |