Bash · lesson 10 of 30 · Decisions and loopsRead a file line by line
while read takes one line per turn and IFS cuts it into fields.
10-while-read.sh Download 10-while-read.sh
#!/usr/app/TurboShell/bin/bash
# IFS= and -r keep every line as it is
n=0
while IFS= read -r line; do
n=$((n + 1))
echo "$n: $line"
done <words.txt
# IFS=, cuts each line at its commas
{
read -r _ # the header line
while IFS=, read -r slot model size temp; do
echo "slot $slot: $model, $size GB, $temp C"
done
} <disks.csv
Terminal
$ bash 10-while-read.sh
1: The NAS keeps files.
2: The files live on disks.
3: Disks fail, so keep a copy of the files.
slot 1: Example HDD A, 8000 GB, 38 C
slot 2: Example HDD A, 8000 GB, 39 C
slot 3: Example HDD B, 12000 GB, 53 C
slot 4: Example SSD C, 1000 GB, 44 CExercise
Print only the disks warmer than 40 C.