| 1 | #!/bin/bash |
| 2 | # |
| 3 | # Usage: |
| 4 | # ./named-ref.test.sh <function name> |
| 5 | |
| 6 | #### pass array by reference |
| 7 | show_value() { |
| 8 | local -n array=$1 |
| 9 | local idx=$2 |
| 10 | echo "${array[$idx]}" |
| 11 | } |
| 12 | shadock=(ga bu zo meu) |
| 13 | show_value shadock 2 |
| 14 | ## stdout: zo |
| 15 | |
| 16 | #### pass assoc array by reference |
| 17 | show_value() { |
| 18 | local -n array=$1 |
| 19 | local idx=$2 |
| 20 | echo "${array[$idx]}" |
| 21 | } |
| 22 | days=([monday]=eggs [tuesday]=bread [sunday]=jam) |
| 23 | show_value days sunday |
| 24 | ## stdout: jam |
| 25 | ## BUG mksh stdout: [monday]=eggs |
| 26 | # mksh note: it coerces "days" to 0? Horrible. |
| 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 have local arrays! |
| 41 | ## BUG mksh stdout-json: "" |
| 42 | ## BUG mksh status: 1 |
| 43 |