Deal with empty character in BASH loop using IFS

Running BASH loops (for loop especially) on a file which contains space/white space characters can be a pain a few times. The reason being the IFS.

  • The Internal Field Separator (IFS) is a special shell variable.
  • IFS is commonly used for word splitting.
  • The default value for $IFS is space, newline, tab.
  • The variable is more commonly used in while loops. Specially when using read command.
  • And, most importantly you can play around this variable and change the value for IFS.

    This article will deal with some common use for IFS.

    Change current IFS

    You can use something like the following in order to remove the current IFS and replace it with something new.

    #!/bin/bash
    
    # Backup current IFS
    oldIFS=$IFS
    
    # Set new IFS here.
    IFS=$'\n'
    
    FILE="/tmp/employee-details.txt"
    
    for name in `/bin/cat $FILE`
    do
    	echo "$name"
    done
    
    # Restore the previous IFS
    IFS=$oldIFS
    

    OR,

    #!/bin/bash
    
    # Backup current IFS
    oldIFS=$IFS
    
    # Set new IFS here.
    IFS=$(echo -en "\n\b")
    
    FILE="/tmp/employee-details.txt"
    
    for name in `/bin/cat $FILE`
    do
    	echo "$name"
    done
    
    # Restore the previous IFS
    IFS=$oldIFS
    

    Using IFS as field separator in while loops

    You can use IFS as a field separator as well.

    The following can be a classic example:

    #!/bin/bash
    
    while IFS=: read user password userid groupid userdesc userhome shell
    do
    	echo "$user -- $userhome -- $shell"
    done < /etc/passwd
    

    No Comments

    Post a Comment

    Time limit is exhausted. Please reload CAPTCHA.