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 |