-1

I have this simple bash script

#!/bin/bash -x

for line in `tail /home/user/line`

 do
      echo $line
 done

but dont know why it echos all words instead of each line below is output

++ tail /home/user/line
+ for line in '`tail /home/user/line`'
+ echo Linux
Linux
+ for line in '`tail /home/user/line`'
+ echo is
is
+ for line in '`tail /home/user/line`'
+ echo a
a
+ for line in '`tail /home/user/line`'
+ echo crappy
crappy
+ for line in '`tail /home/user/line`'
+ echo OS
OS
+ for line in '`tail /home/user/line`'
+ echo Do
Do
+ for line in '`tail /home/user/line`'
+ echo you
you
+ for line in '`tail /home/user/line`'
+ echo 'agree?'
agree?
+ for line in '`tail /home/user/line`'
+ echo Unix
Unix
+ for line in '`tail /home/user/line`'
+ echo is
is
+ for line in '`tail /home/user/line`'
+ echo much
much
+ for line in '`tail /home/user/line`'
+ echo better
better
+ for line in '`tail /home/user/line`'
+ echo Or
Or
+ for line in '`tail /home/user/line`'
+ echo maybe
maybe
+ for line in '`tail /home/user/line`'
+ echo Solaris
Solaris
+ for line in '`tail /home/user/line`'
+ echo 'OS?'
OS?
+ for line in '`tail /home/user/line`'
+ echo Linux
Linux
+ for line in '`tail /home/user/line`'
+ echo Linux
Linux
+ for line in '`tail /home/user/line`'
+ echo 'Linux!'
Linux!

here is the text file

Linux is a crappy OS

Do you agree?

Unix is much better
Or maybe Solaris OS?
Linux Linux Linux!

Any idea why its not not echoing line by line? Thanks

grant tailor
  • 505
  • 2
  • 6
  • 13

1 Answers1

1

if you want to print the lines, you need to use while read line using while read you will read line by line, for example:

while read line;do echo $line ;done < /etc/passwd
c4f4t0r
  • 5,301
  • 3
  • 31
  • 42
  • where is the code? – grant tailor Mar 10 '15 at 20:40
  • @granttailor i edited my answer. – c4f4t0r Mar 10 '15 at 20:56
  • Just to clarify, when you pass data to a for loop, it considers both spaces and returns as a break in the input. It's so you can do stuff like: for i in \`pidof fooprocess\` ; do kill -9 $i ; done or for field in \`cat blah.csv | cut -d , -f 2-4 | sed 's/,/\ /g' \` ; echo something something $field ; done – Some Linux Nerd Mar 10 '15 at 22:25