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