Shell Loops with for, while and until
One objective, phrased as "process file, command line input" - so the forms that matter are the ones that read a file and the ones that read a command's output. Seven loop forms are run here, and one common mistake is shown failing.
Shell Scripts Guide 63 of 67 Beginner
- OSRHEL 10.0
- Kernel6.12.0-55.9.1.el10_0
- dnf4.20.0
- Flatpak1.16.0
- TimeAbout 12 min
while IFS= read -r LINE is the correct way to read a file line by line. IFS= stops leading and trailing whitespace being stripped and -r stops backslashes being interpreted. Without both, a line containing a backslash or indentation comes out altered.
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| RHCSA-A01 | 192.168.0.31 | RHEL 10.0 | Practice node (graded) - spare /dev/sda | 2 Core | 4 GB | 50 GB + 15 GB |
This guide includes
Use this for one objective phrased as processing files and command-line input. This matters because the loop form follows from the input - and brace expansion happens before variables exist, which is why one common attempt quietly produces nothing useful.
- running seven loop forms, and seeing which suits which input
- finding why
{1..$TOP}does not do what it appears to - choosing the form from the input rather than from habit
Before you start
- A shell.
- The session writes and removes
~/scripts.
-
Seven forms, run
-
Why `{1..$TOP}` does not work