Skip to content

Instantly share code, notes, and snippets.

@cig0
Created February 16, 2015 01:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cig0/86d143b7312919167539 to your computer and use it in GitHub Desktop.
Save cig0/86d143b7312919167539 to your computer and use it in GitHub Desktop.
typeset - arrays
#!/bin/bash
# Sum a set of arrays and assign the result indirectly, also printing each intermediary result (without portability workarounds)
# sum name arrname [ arrname ... ]
function sum {
typeset -n _result=$1 _arr
typeset IFS=+
_result=0
for _arr in "${@:2}"; do # Demonstrate the special property of "for" on a nameref.
(( _result += ${_arr[*]} ))
printf '%s = %d\n' "${!_result}" "$_result" # Demonstrate the special property of ${!ref} on a nameref.
done
}
a=(1 2 3) b=(6 5 4) c=(2 4 6)
sum total a b c
printf 'Final value of "total" is: %d\n' "$total"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment