Line by line in BASH, coping with the spaces

When I do something like this:

for line in `cat some_file`
    <whatever with> $line

It works fine when there are no spaces in the lines in $line. But if there are spaces, it does <whatever> to each expression between the spaces.

Two neat tricks for coping with is.

1. Change the internal field separator ($IFS) to only separate on newline:


And carry on with your normal loop.

2. Use a read in a while loop instead:

cat filename | while read line; do
    echo $line



About Miller

I live in Second Life with my shoulder pet Logan. I write code for her and I sometimes greet people in the Virtual Kennel Club Dog Park at Turing Isle: Isle/128/126/27/ I also write in my own Blog at and sometimes even on FB.
This entry was posted in Linux Stuff and tagged , , , . Bookmark the permalink.

3 Responses to Line by line in BASH, coping with the spaces

  1. Rodnee says:

    Thanks. I was trying to figure out if changing the IFS would be system wide or not. But the read in while loop worked for me. Thanks again.

    • Miller says:

      Hey Rodnee, IFS will return to its original value once the script finishes. Or, if you just set it inside a block of code, it will revert when that block of code finishes. But looking at your page, I think you already got that covered (-:

  2. Pingback: bash – working with spaces « pseudo-scripter

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s