Dit deel is nog niet vertaald. Je ziet de Engelse tekst.
$ als gewone gebruiker# als root (of met sudo)
Vaardigheden in dit hoofdstuk
- Lijsten en sleutel-waardegegevens opslaan in arrays
Know what arrays are
An array is like a table with one column: each cell has a number (the index or subscript) and a value.
- bash arrays have one dimension. The index starts at 0.
- Associative arrays (bash 4.0 and newer) use strings as index.
Make an array
An array is made when you assign a value with an index, or with declare -a.
a[1]=foo
echo ${a[1]}
foo
declare -a a
days=(Sun Mon Tue Wed Thu Fri Sat)
days=([0]=Sun [1]=Mon [2]=Tue [3]=Wed [4]=Thu [5]=Fri [6]=Sat)Onthoud
Use braces to read an element: ${days[1]}. $days[1] is wrong: it prints the first element and the text [1].
Use an array: count files by hour
A real example: count how many files in a directory were changed in each hour of the day. The hour (0–23) is the index.
#!/bin/bash
# hours: script to count files by modification time
usage () {
echo "usage: ${0##*/} directory" >&2
}
# Check that argument is a directory
if [[ ! -d "$1" ]]; then
usage
exit 1
fi
# Initialize array
for i in {0..23}; do hours[i]=0; done
# Collect data
for i in $(stat -c %y "$1"/* | cut -c 12-13); do
j="${i#0}"
((++hours[j]))
((++count))
done
# Display data
echo -e "Hour\tFiles\tHour\tFiles"
echo -e "----\t-----\t----\t-----"
for i in {0..11}; do
j=$((i + 12))
printf "%02d\t%d\t%02d\t%d\n" \
"$i" "${hours[i]}" "$j" "${hours[j]}"
done
printf "\nTotal files = %d\n" "$count"stat -c %yprints the change time;cut -c 12-13takes the hour.${i#0}removes a leading zero, so08is not read as an octal number.
Print all elements
[*] and [@] give all elements. As with positional parameters, only "${array[@]}" keeps each element as one word.
Count elements and find the indexes
${#array[@]} is the number of elements. ${!array[@]} lists the indexes that are used (arrays can have gaps).
Fill arrays with read -a and +=
read -a puts the words of a line into an array. += adds elements to the end.
Read a file into an array
mapfile (also called readarray) reads each line of a file into one element.
Slice and sort arrays
${array[@]:start:count} takes a part. bash has no sort command for arrays, but a pipeline through sort does the job.
Delete arrays and elements
unset deletes a whole array or one element. Assigning an empty value does not delete.
Use associative arrays
declare -A makes an array with text as index. Perfect for key → value data.
declare -A colors
colors["red"]="#ff0000"
colors["green"]="#00ff00"
colors["blue"]="#0000ff"
echo "${colors["blue"]}"
#0000ff
for k in "${!colors[@]}"; do echo "$k = ${colors[$k]}"; donedeclare -A hits
while read -r ip _; do
((hits[$ip]++))
done < /var/log/nginx/access.log
for ip in "${!hits[@]}"; do
printf "%6d %s\n" "${hits[$ip]}" "$ip"
done | sort -rn | head- Associative arrays must be declared with
declare -A. The order of the keys is not fixed. - Two dimensions can be simulated with a key like
"$row,$col":grid["2,3"]=x.
Summary of the chapter
arr=(a b c), ${arr[i]}, "${arr[@]}", ${#arr[@]}, ${!arr[@]}, arr+=(), mapfile, unset, declare -A.
1How do you print every element of files as one word each, also with spaces?
for f in "${files[@]}"; do echo "$f"; done.
2Which command reads all lines of a file into an array?
mapfile -t lines < file (or readarray).
3How do you make an array with names as index?
declare -A name, then name["key"]=value.