97ed5123d7fc690d29e3da15bb419c55b19287ca
[platform/upstream/bash.git] / examples / functions / array-stuff
1 # usage: reverse arrayname
2 reverse()
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
25 A=(1 2 3 4 5 6 7)
26 echo "${A[@]}"
27 reverse A
28 echo "${A[@]}"
29 reverse A
30 echo "${A[@]}"
31
32 # unset last element of A
33 alen=${#A[@]}
34 unset A[$alen-1]
35 echo "${A[@]}"
36
37 # ashift -- like shift, but for arrays
38
39 ashift()
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
61 ashift A 2
62 echo "${A[@]}"
63
64 ashift A
65 echo "${A[@]}"
66
67 ashift A 7
68 echo "${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.
72 array_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
97 A=(3 1 4 1 5 9 2 6 5 3 2)
98 array_sort A
99 echo "${A[@]}"
100
101 A=(3 1 4 1 5 9 2 6 5 3 2)
102 array_sort -u A
103 echo "${A[@]}"