summaryrefslogtreecommitdiff
path: root/examples/functions/array-stuff
blob: 97ed5123d7fc690d29e3da15bb419c55b19287ca (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
# 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[@]}"