blob: e6316c76dbd6c814aa0e84e9f52b9e5c01dd4f57 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
|
#
# Chet Ramey <chet.ramey@case.edu>
#
# Copyright 1999 Chester Ramey
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# TThis program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# usage: reverse arrayname
reverse()
{
local -a R
local -i i
local rlen temp
# make r a copy of the array whose name is passed as an arg
eval R=\( \"\$\{$1\[@\]\}\" \)
# reverse R
rlen=${#R[@]}
for ((i=0; i < rlen/2; i++ ))
do
temp=${R[i]}
R[i]=${R[rlen-i-1]}
R[rlen-i-1]=$temp
done
# and assign R back to array whose name is passed as an arg
eval $1=\( \"\$\{R\[@\]\}\" \)
}
A=(1 2 3 4 5 6 7)
echo "${A[@]}"
reverse A
echo "${A[@]}"
reverse A
echo "${A[@]}"
# unset last element of A
alen=${#A[@]}
unset A[$alen-1]
echo "${A[@]}"
# ashift -- like shift, but for arrays
ashift()
{
local -a R
local n
case $# in
1) n=1 ;;
2) n=$2 ;;
*) echo "$FUNCNAME: usage: $FUNCNAME array [count]" >&2
exit 2;;
esac
# make r a copy of the array whose name is passed as an arg
eval R=\( \"\$\{$1\[@\]\}\" \)
# shift R
R=( "${R[@]:$n}" )
# and assign R back to array whose name is passed as an arg
eval $1=\( \"\$\{R\[@\]\}\" \)
}
ashift A 2
echo "${A[@]}"
ashift A
echo "${A[@]}"
ashift A 7
echo "${A[@]}"
# Sort the members of the array whose name is passed as the first non-option
# arg. If -u is the first arg, remove duplicate array members.
array_sort()
{
local -a R
local u
case "$1" in
-u) u=-u ; shift ;;
esac
if [ $# -eq 0 ]; then
echo "array_sort: argument expected" >&2
return 1
fi
# make r a copy of the array whose name is passed as an arg
eval R=\( \"\$\{$1\[@\]\}\" \)
# sort R
R=( $( printf "%s\n" "${A[@]}" | sort $u) )
# and assign R back to array whose name is passed as an arg
eval $1=\( \"\$\{R\[@\]\}\" \)
return 0
}
A=(3 1 4 1 5 9 2 6 5 3 2)
array_sort A
echo "${A[@]}"
A=(3 1 4 1 5 9 2 6 5 3 2)
array_sort -u A
echo "${A[@]}"
|