← Linux and the Command Line Lesson 49 of 51 · 10 XP

Loops: for and while

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

for goes through a list of words:

for name in Anna Bob Vicky; do
    echo "Hello, $name"
done

for f in *.log; do               # all the .log files in the folder
    gzip "$f"
done

for i in $(seq 1 5); do          # the numbers from 1 to 5
    echo "$i"
done

while repeats as long as a command succeeds:

i=1
while [ "$i" -le 3 ]; do
    echo "$i"
    i=$((i + 1))
done

The most common pattern is reading the input or a file line by line:

while read -r line; do
    echo "line: $line"
done < input.txt

-r stops read from treating \ as a special character. Always write it.

break and continue work as in other languages.

Don't use for line in $(cat file) to read lines: it cuts the text into words, not lines.

Task. For each line of the input (these are file names), create a file, and then print the sorted list of the created files with the size of each, which equals the length of its name: write the name itself into the file with printf "%s" "$name". The output format is name size.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.