Thursday, November 6, 2014

How to Handle the Line with spaces in Shell for loop


One of the error that was faced while doing automation in Bash,ksh is that
when you use the for loop to loop a records that have spaces ,then it takes each word in a line and loops it.

This is due to the Setting of the Variable IFS

     
man bash


   IFS    The Internal Field Separator that is used for word splitting after expansion and to split lines into words with the  read  builtin  command.
              The default value is ‘‘<space><tab><newline>’’.

As it states above , the default IFS make it to happen that way.

How to overcome it, is by using the below where you can say to consider only the New Line as Internal Field separator.

  IFS=$'\n' 
  for BLIST in `cat $FileList`
   do
    echo "$BLIST"
    .
    .
    .
   done


Sample File :

  $cat FileList 
      A B C
      AA FF EE
      DD SS RR