Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

I was originally of the impression that

$ ./myprog
moo[CTRL-D]

is exactly the same as

$ echo moo > cow
$ ./myprog < cow

But I found that myprog always counts one more \n in the second version than in the first. Why is this?

Turns out wc does the same thing...

$ wc -l
moo[CTRL-D]0

(Apparently zero lines is possible?)

$ echo moo > cow
$ wc -l < cow
1

Can anyone explain this to me?

share|improve this question

1 Answer 1

up vote 4 down vote accepted

echo appends a newline, unless you tell it not to, by putting -n first or \c at the end, or putting -e first and \c at the end or... you really don't want to know all the varieties of echo. Use printf moo > cow and you'll have a file with zero lines.

share|improve this answer
    
+1: printf is much more portable than echo. –  jw013 Sep 4 '12 at 0:21
    
Technically, the only possible file with zero lines is empty file. A non-empty file without trailing LF is a file without proper termination of the last line. Could you fix misleading wording in the answer? –  Incnis Mrsi Aug 19 at 18:10

Your Answer

 
discard

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