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 33Naam in het boek: Flow Control: Looping with for

Loop with for

for is the most used loop. It walks through a list of words: file names, users, servers, numbers. bash has two forms: the traditional shell form over a list, and the C language form with a counter. This chapter shows both, and adds a loop to the report script.

  • 7 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)

33.1

Use the traditional form

for variable in words; do … done runs the commands once for each word.

for i in A B C D; do echo "$i"; done
A
B
C
D
for i in {A..D}; do echo "$i"; done
for i in distros*.txt; do echo "$i"; done
for i in $(seq 1 3); do echo "Round $i"; done
  • The list can come from words, brace expansion, wildcards or command substitution.
  • If in words is left out, for uses the positional parameters ("$@").

33.2

Loop over files safely

Wildcards in for give one word per file, also with spaces. Check that a match exists: if no file matches, the pattern itself is the word.

count lines of all .txt files
for i in ./*.txt; do
    if [[ -e "$i" ]]; then
        echo "$i: $(wc -l < "$i") lines"
    fi
done

Op het werk

for f in ./*.log; do gzip "$f"; done works with every file name. Do not loop over $(ls): it breaks names with spaces.

33.3

Find the longest word

A real example: read each file given on the command line and find its longest word.

longest-word
#!/bin/bash
 
# longest-word: find longest string in a file
 
for i; do
    if [[ -r "$i" ]]; then
        max_word=
        max_len=0
        for j in $(strings "$i"); do
            len="$(echo -n "$j" | wc -c)"
            if (( len > max_len )); then
                max_len="$len"
                max_word="$j"
            fi
        done
        echo "$i: '$max_word' ($max_len characters)"
    fi
done
  • for i; alone loops over all arguments.
  • strings prints the readable words from any file. Here the unquoted $(strings …) is wanted: it splits the text into words.

Notitie

Why i? Old FORTRAN used the letters I to N for whole numbers, so programmers have used i, j, k as loop counters ever since.

33.4

Use the C language form

for (( start; condition; step )) works with a counter, like in C.

simple_counter
#!/bin/bash
 
# simple_counter: demo of C style for command
 
for (( i=0; i<5; i=i+1 )); do
    echo "$i"
done
simple_counter
0
1
2
3
4
for (( i=10; i>0; i-=2 )); do echo -n "$i "; done; echo
10 8 6 4 2
PartRunsExample
startonce, before the loopi=0
conditionbefore each round; the loop stops when it is falsei<5
stepafter each roundi=i+1 or i++

Commando's in deze les

33.5

Add a loop to the report

Show the space of each home directory, with the number of files and directories, in a loop.

report_home_space with for
report_home_space () {
    local format="%8s%10s%10s\n"
    local i dir_list total_files total_dirs total_size user_name
 
    if [[ "$(id -u)" -eq 0 ]]; then
        dir_list=/home/*
        user_name="All Users"
    else
        dir_list="$HOME"
        user_name="$USER"
    fi
 
    echo "<h2>Home Space Utilization ($user_name)</h2>"
 
    for i in $dir_list; do
        total_files="$(find "$i" -type f | wc -l)"
        total_dirs="$(find "$i" -type d | wc -l)"
        total_size="$(du -sh "$i" | cut -f 1)"
 
        echo "<h3>$i</h3>"
        echo "<pre>"
        printf "$format" "Dirs" "Files" "Size"
        printf "$format" "----" "-----" "----"
        printf "$format" "$total_dirs" "$total_files" "$total_size"
        echo "</pre>"
    done
    return
}

33.6

Use for in daily admin work

for makes one command work on many servers, users or files.

for h in web1 web2 db1; do ssh "$h" uptime; done
for u in ana ben; do sudo useradd -m "$u"; done
for f in ./*.jpeg; do mv -- "$f" "${f%.jpeg}.jpg"; done
  • The last example renames all .jpeg files to .jpg with parameter expansion (next chapter).

33.7

Summary of the chapter

for x in list for words and files; for (( ; ; )) for counters; always quote "$x".

1Which loop prints the numbers 1 to 10?

for i in {1..10}; do echo "$i"; done or for (( i=1; i<=10; i++ )); do echo "$i"; done.

2What does for i; do … done loop over?

The positional parameters (all arguments of the script or function).

3Why is for f in $(ls) a bad idea?

File names with spaces are split into several words. Use for f in ./*.

Oefenen

Alle commando's in dit hoofdstuk