1# usage: reverse arrayname
2reverse()
3{
4	local -a R
5	local -i i
6	local rlen temp
7
8	# make r a copy of the array whose name is passed as an arg
9	eval R=\( \"\$\{$1\[@\]\}\" \)
10
11	# reverse R
12	rlen=${#R[@]}
13
14	for ((i=0; i < rlen/2; i++ ))
15	do
16		temp=${R[i]}
17		R[i]=${R[rlen-i-1]}
18		R[rlen-i-1]=$temp
19	done
20
21	# and assign R back to array whose name is passed as an arg
22	eval $1=\( \"\$\{R\[@\]\}\" \)
23}
24
25A=(1 2 3 4 5 6 7)
26echo "${A[@]}"
27reverse A
28echo "${A[@]}"
29reverse A
30echo "${A[@]}"
31
32# unset last element of A
33alen=${#A[@]}
34unset A[$alen-1]
35echo "${A[@]}"
36
37# ashift -- like shift, but for arrays
38
39ashift()
40{
41	local -a R
42	local n
43
44	case $# in
45	1)	n=1 ;;
46	2)	n=$2 ;;
47	*)	echo "$FUNCNAME: usage: $FUNCNAME array [count]" >&2
48		exit 2;;
49	esac
50
51	# make r a copy of the array whose name is passed as an arg
52	eval R=\( \"\$\{$1\[@\]\}\" \)
53
54	# shift R
55	R=( "${R[@]:$n}" )
56
57	# and assign R back to array whose name is passed as an arg
58	eval $1=\( \"\$\{R\[@\]\}\" \)
59}
60
61ashift A 2
62echo "${A[@]}"
63
64ashift A
65echo "${A[@]}"
66
67ashift A 7
68echo "${A[@]}"
69
70# Sort the members of the array whose name is passed as the first non-option
71# arg.  If -u is the first arg, remove duplicate array members.
72array_sort()
73{
74	local -a R
75	local u
76
77	case "$1" in
78	-u)	u=-u ; shift ;;
79	esac
80
81	if [ $# -eq 0 ]; then
82		echo "array_sort: argument expected" >&2
83		return 1
84	fi
85
86	# make r a copy of the array whose name is passed as an arg
87	eval R=\( \"\$\{$1\[@\]\}\" \)
88
89	# sort R
90	R=( $( printf "%s\n" "${A[@]}" | sort $u) )
91
92	# and assign R back to array whose name is passed as an arg
93	eval $1=\( \"\$\{R\[@\]\}\" \)
94	return 0
95}
96
97A=(3 1 4 1 5 9 2 6 5 3 2)
98array_sort A
99echo "${A[@]}"
100
101A=(3 1 4 1 5 9 2 6 5 3 2)
102array_sort -u A
103echo "${A[@]}"
104