5

Does echo -n | ... send an EOF to the pipe? I.e.,

echo -n | sth

Will sth recieve an EOF on its stdin?

2
  • 3
    please note that : 1) you should replace echo -n "something" (shell dependant, and OS dependent) with : printf "%s" "something" (the portable way. ) see unix.stackexchange.com/a/65819/27616 : And 2) if you intend to pipe to another command, if that command expect a TEXT, a (last) line without a terminating "\n" is often not considered valid and will be discarded... ex: printf "a\nb\nc\n" | wc -l # 3 lines, 3 words, 6 chars printf "a\nb\nc" | wc # 2 lines, 3 words, 5 chars! , ie wc -l doesn't count the last line, even though it has characters on it! Commented Sep 21, 2020 at 12:20
  • It doesn't make sense to talk of "sending" or "receiving" end-of-file. It's a condition, not some kind of data. Commented Sep 22, 2021 at 7:33

2 Answers 2

14

There is no EOF that is represented as data in a file or stream. It is merely a status associated with the file descriptor.

When the echo terminates (which will be almost immediately), the write end of the pipe is closed.

The next time sth reads (assuming it has read all data previously written to the file) the pipe status changes to EOF and the read issued by sth returns with the EOF condition. The process can continue with any processing it requires, it just cannot read any more from the pipe.

2
  • 1
    “it just cannot read any more from the pipe” — that's true here, but it wouldn't be the case with a named pipe. With a named pipe, the reader could continue reading and would receive data if another process opens the named pipe for writing and writes to it. Commented Sep 20, 2020 at 17:44
  • @Gilles'SO-stopbeingevil' Agreed -- I answered the question on the basis of a shell simple anonymous pipe. I believe a construct like { echo; sleep 5; echo bar; } | cat lets all three processes inherit the pipe fd for writing. Commented Sep 20, 2020 at 17:59
5

Yes. A program that reads from a pipe sees an end-of-file on the pipe when the program that writes to the pipe closes the writing end. More precisely, the end-of-file event happens when the last file descriptor that was open on the pipe gets closed. Ways to close a file descriptor include explicit closing and a process exiting.

Here there's just one process writing to the pipe and running echo -n, which depending on the shell either writes -n and a newline, or nothing. When that process has finished writing and exits, the writing end of the pipe is closed, so sth sees EOF on the pipe. (It's also possible that the shell runs the left-hand side of the pipe without forking, in which case the shell closes the pipe explicitly when it's done writing: this optimization doesn't make any difference to the right-hand side of the pipe.)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .