Geavanceerd
Zoeken inSamenvattingen
Zo zoek je
  • Woorden vinden lestitels, tekst en code. Filter op soort (gidsen, cursussen, programma's, boeken) of blijf in dit boek.
  • book:rhcsa en ch:8 maken de zoektocht kleiner; #code vindt een woord alleen in commando's van de lessen.
  • "twee woorden" vindt precies die zin.
  • Gewone woorden vinden namen, teksten en voorbeelden.
  • ↑ ↓ bewegen · Enter openen · Esc sluiten · / zoeken
Probeer:

Hoofdstuk 35Naam in het boek: Arrays

Use arrays

A normal variable holds one value. An array holds many values, each with an index. bash has indexed arrays (numbers as index, from 0) and associative arrays (text as index, like a dictionary). This chapter shows how to make, fill, read, sort and delete arrays.

  • 11 Lessen
  • 6 Commando's
  • 1 Labs

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

35.1

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.

35.2

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].

Commando's in deze les

35.3

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.

hours
#!/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 %y prints the change time; cut -c 12-13 takes the hour.
  • ${i#0} removes a leading zero, so 08 is not read as an octal number.

35.4

Print all elements

[*] and [@] give all elements. As with positional parameters, only "${array[@]}" keeps each element as one word.

animals=("a dog" "a cat" "a fish")
for i in ${animals[*]}; do echo "$i"; done
for i in "${animals[*]}"; do echo "$i"; done
a dog a cat a fish
for i in "${animals[@]}"; do echo "$i"; done
a dog
a cat
a fish

Commando's in deze les

35.5

Count elements and find the indexes

${#array[@]} is the number of elements. ${!array[@]} lists the indexes that are used (arrays can have gaps).

a[100]=foo
echo ${#a[@]}
1
echo ${#a[100]}
3
foo=([2]=a [4]=b [6]=c)
for i in "${!foo[@]}"; do echo "$i"; done
2
4
6
  • ${#a[100]} is the length of element 100 ("foo" = 3), not the number of elements.

Commando's in deze les

35.6

Fill arrays with read -a and +=

read -a puts the words of a line into an array. += adds elements to the end.

read -a words <<< "one two three"
echo "${words[1]}"
two
foo=(a b c)
foo+=(d e f)
echo "${foo[@]}"
a b c d e f

35.7

Read a file into an array

mapfile (also called readarray) reads each line of a file into one element.

mapfile -t lines < /etc/hosts
echo "${#lines[@]}"
echo "${lines[0]}"
127.0.0.1   localhost localhost.localdomain
mapfile -t users < <(cut -d: -f1 /etc/passwd)
  • -t removes the new line at the end of each line.

Commando's in deze les

35.8

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.

foo=(a b c d e f)
echo "${foo[@]:2:3}"
c d e
a=(f e d c b a)
a_sorted=($(for i in "${a[@]}"; do echo "$i"; done | sort))
echo "${a_sorted[@]}"
a b c d e f

Notitie

The sort trick splits elements with spaces. For safe sorting, use mapfile -t sorted < <(printf '%s\n' "${a[@]}" | sort).

35.9

Delete arrays and elements

unset deletes a whole array or one element. Assigning an empty value does not delete.

foo=(a b c d e f)
unset 'foo[2]'
echo "${foo[@]}"
a b d e f
unset foo
echo "${foo[@]}"
  • Put foo[2] in quotes for unset: otherwise the shell may treat [2] as a wildcard.
  • foo= only empties element 0.

35.10

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]}"; done
count requests per IP from a web log
declare -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.

Commando's in deze les

35.11

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.

Oefenen

Alle commando's in dit hoofdstuk