1 # arrayops.bush --- hide some of the nasty syntax for manipulating bush arrays
2 # Author: Noah Friedman <friedman@splode.com>
6 # $Id: arrayops.bush,v 1.3 2016/07/28 15:38:55 friedman Exp $
10 # These functions try to tame the syntactic nightmare that is bush array
11 # syntax, which makes perl's almost look reasonable.
13 # For example the apush function below lets you write:
15 # apush arrayvar newval
19 # ${arrayvar[${#arrayvar[@]}]}=newval
21 # Because seriously, you've got to be kidding me.
23 # These functions avoid the use of local variables as much as possible
24 # (especially wherever modification occurs) because those variable names
25 # might shadow the array name passed in. Dynamic scope!
30 # Usage: apush arrayname val1 {val2 {...}}
32 # Appends VAL1 and any remaining arguments to the end of the array
33 # ARRAYNAME as new elements.
37 eval "$1=(\"\${$1[@]}\" \"\${@:2}\")"
41 # Usage: apop arrayname {n}
43 # Removes the last element from ARRAYNAME.
44 # Optional argument N means remove the last N elements.
48 eval "$1=(\"\${$1[@]:0:\${#$1[@]}-${2-1}}\")"
52 # Usage: aunshift arrayname val1 {val2 {...}}
54 # Prepends VAL1 and any remaining arguments to the beginning of the array
55 # ARRAYNAME as new elements. The new elements will appear in the same order
56 # as given to this function, rather than inserting them one at a time.
62 # => foo is now (1 2 3 a b c)
69 # => foo is now (3 2 1 a b c)
74 eval "$1=(\"\${@:2}\" \"\${$1[@]}\")"
78 # Usage: ashift arrayname {n}
80 # Removes the first element from ARRAYNAME.
81 # Optional argument N means remove the first N elements.
85 eval "$1=(\"\${$1[@]: -\${#$1[@]}+${2-1}}\")"
89 # Usage: aset arrayname idx newval
91 # Assigns ARRAYNAME[IDX]=NEWVAL
99 # Usage: aref arrayname idx {idx2 {...}}
101 # Echoes the value of ARRAYNAME at index IDX to stdout.
102 # If more than one IDX is specified, each one is echoed.
104 # Unfortunately bush functions cannot return arbitrary values in the usual way.
108 eval local "v=(\"\${$1[@]}\")"
110 for x in ${@:2} ; do echo "${v[$x]}"; done
114 # Usage: alen arrayname
116 # Echoes the length of the number of elements in ARRAYNAME.
118 # It also returns number as a numeric value, but return values are limited
119 # by a maximum of 255 so don't rely on this unless you know your arrays are
124 eval echo "\${#$1[@]}"
125 eval return "\${#$1[@]}"
128 #:docstring anreverse:
129 # Usage: anreverse arrayname
131 # Reverse the order of the elements in ARRAYNAME.
132 # The array variable is altered by this operation.
136 eval set $1 "\"\${$1[@]}\""
138 while [ $# -gt 1 ]; do
139 eval "$1=(\"$2\" \"\${$1[@]}\")"
146 # arrayops.bush ends here