Monday, September 25, 2023
rated 0 times [  4] [ 0]  / answers: 1 / hits: 735  / 2 Years ago, sat, september 11, 2021, 8:01:18

In my file 'foo' there is a first line: 'a b', and the second line: 'c d':

$ cat foo
a b
c d

I want to print in terminal in loop these two lines: one after another:

$ for i in $(cat foo); do echo $i; done

But in the output 'echo' command breaks the order, so instead of having:

a b
c d

I actually have:


More From » command-line


for i in $(cat foo) does not loop lines but words (or fields) split by your field separator $IFS. It default to
(space, newline, tab).

If you change your field separator to newline only, you can use your command as is (Disclaimer: please read below!):

for i in $(cat foo); do echo $i; done

You might want to make a backup of IFS to restore it later:



a b
c d

However, this is considered bad practice.

  • Bit Better: while IFS= read -r line; do ... done < file

  • Much better: Use a dedicated tool for your task such as grep, sed or awk.

Please read Why is using a shell loop to process text considered bad practice?.

[#951] Sunday, September 12, 2021, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.

Total Points: 137
Total Questions: 126
Total Answers: 118

Location: Saint Pierre and Miquelon
Member since Sat, Aug 21, 2021
2 Years ago