How To Loop Through A Unix File - Good & Bad

BACKGROUND

There may be times when looping through the contents of a Unix file as an input to a group of actions is required. This document demonstrates the 'bad' (and unfortunately common) way of doing this, and the more efficient 'good' way.

The 'bad' way is so, because it (a) pre-allocates memory, and thus can impact the overall system performance, especially with large files; and (b) when a line contains more than one value, each values is treated as a line, therefore results can be unpredictable.

THE 'BAD' WAY

      for LINE in `cat ${FILE}`
      do
         echo ${LINE}
      done

THE 'GOOD' WAY

      while read LINE
      do
         echo ${LINE}
      done < ${FILE}
© copyright 2001-2014 ABCdba.com | all rights reserved