Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Say I have this file:

hello world

This program


for i in $(cat $1); do
    echo "tester: $i"


tester: hello
tester: world
tester: hello
tester: world

I'd like to have the for iterate over each line individually ignoring whitespaces though, i.e. the last two lines should be replaced by

tester: hello world

Using quotes for i in "$(cat $1)"; results in i being assigned the whole file at once. What should I change?

share|improve this question
up vote 35 down vote accepted

With for and IFS:


IFS=$'\n'       # make newlines the only separator
set -f          # disable globbing
for i in $(cat "$1"); do
  echo "tester: $i"

Or with read (no more cat):


while IFS= read -r line; do
  echo "tester: $line"
done < "$1"
share|improve this answer
thanks, I didn't know one could < into a whole loop. Although it makes perfectly sense now I saw it – Tobias Kienzler Feb 7 '11 at 11:06
I see IFS \ read -r line' in second example. Is really IFS=` needed ? IMHO it enough to say : while read -r line; do echo "tester: $line"; done < "$1" – Grzegorz Wierzowiecki Mar 19 '12 at 16:45
@GrzegorzWierzowiecki IFS= turns off the stripping of leading and trailing whitespace. See In while IFS= read.., why does IFS have no effect? – Gilles Jan 12 '14 at 0:29

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.