Tech and travel

Using while loops with read

2007-05-08

If you want to loop over values in a file, the read command in Linux/Unix is very useful. It reads a line from a file, and assigns as many variables as you specify as parameters to the values in that line. Combined with a while loop, you can read the values and process them. Here’s an example :

while read customernr
do
  <some_script> $customernr
done < customers.txt

This loops over all the lines in the customers.txt file. This file contains one customer number per line. Then we can reference this customer number as $customernr, and process it. Here that value is given as a parameter to some script.

Thanks to Steve Parker’s website for reminding me of the syntax of the while loop. It’s funny how Google has replaced reading man pages.

Copyright (c) 2024 Michel Hollands