Preventing white spaces to be a delimiter in a for loop in bash

Using a for loop in bash to read a file line by line can sometimes be very annoying, here’s a little trick to make it actually red it LINE BY LINE.

Right before you run your for loop in your script, set this:

IFS=\n

With the above environment variable set, you tell bash that the delimiter is now a new-line (\n) instead of a white space.

Example:

Let’s say you have a text file (foo.txt) containing the following lines:

1 2 3
a b c

Running the following code

#!/bin/bash
for LINE in `cat foo.txt`; do
 echo $LINE;
done

will result in this output:

1
2
3
a
b
c

That’s not what we want, we want per line, so we add the IFS environment variable to the code, like this:

#!/bin/bash
IFS=\n
for LINE in `cat foo.txt`; do
 echo $LINE;
done

There you go, the output is now:

1 2 3
a b c

The delimiter is only changed for the duration of the script, so you don’t have to reset it or anything.
Happy coding!

4 thoughts on “Preventing white spaces to be a delimiter in a for loop in bash

  1. Hi Ushi, thanks for your comment, though that won’t work.
    Atleast, i tried, but failed.

    mark@talitha:~$ while read LINE; do echo $LINE; done < foo.txt 1 2 3 4 5 a b c

  2. This output is strange, why is there a “4” and a “5”? I got this:

    [ushi@cato tmp]$ while read LINE; do echo $LINE; done < test
    1 2 3
    a b c
    [ushi@cato tmp]$ cat test
    1 2 3
    a b c

Leave a Reply

Your email address will not be published.

*