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 |
|
18 |
### pass assoc array by reference |
19 |
show_value() { |
20 |
local -n array=$1 |
21 |
local idx=$2 |
22 |
echo "${array[$idx]}" |
23 |
} |
24 |
days=([monday]=eggs [tuesday]=bread [sunday]=jam) |
25 |
show_value days sunday |
26 |
# stdout: jam |
27 |
|
28 |
### pass local array by reference, relying on DYNAMIC SCOPING |
29 |
show_value() { |
30 |
local -n array=$1 |
31 |
local idx=$2 |
32 |
echo "${array[$idx]}" |
33 |
} |
34 |
caller() { |
35 |
local shadock=(ga bu zo meu) |
36 |
show_value shadock 2 |
37 |
} |
38 |
caller |
39 |
# stdout: zo |
40 |
# mksh appears not to hav elocal arrays! |
41 |
# BUG mksh stdout-json: "" |
42 |
# BUG mksh status: 1 |
43 |
|
44 |
### Var ref with ${!a} |
45 |
a=b |
46 |
b=c |
47 |
echo ref ${!a} |
48 |
# Woah mksh has a completely different behavior -- var name, not var ref. |
49 |
# stdout: ref c |
50 |
# BUG mksh stdout: ref a |
51 |
# N-I dash/zsh stdout-json: "" |
52 |
|
53 |
### Bad var ref with ${!a} |
54 |
#set -o nounset |
55 |
a='bad var name' |
56 |
echo ref ${!a} |
57 |
# Woah even dash implements this! |
58 |
# stdout-json: "ref\n" |
59 |
# BUG mksh stdout: ref a |
60 |
# N-I dash/zsh stdout-json: "" |
61 |
|
62 |
### Nested ${} |
63 |
bar=ZZ |
64 |
echo ${foo:-${bar}} |
65 |
# stdout: ZZ |