Trailing new line after piping to a command: is there any standard? Trailing new line after piping to a command: is there any standard? bash bash

Trailing new line after piping to a command: is there any standard?


So I was wondering: why is this different behaviour? Is there anything POSIX suggests about this?

Some commands (like for example printf) are simple interface to the libc library calls (e.g. printf()) which don't add \n automatically. Most *NIX text processing commands would add a \n on the end of the last line.

From the Definitions of POSIXv7, a textual line has to have a newline on the end:

3.206 Line

A sequence of zero or more non- <newline> characters plus a terminating character.

If the newline is missing, it becomes this:

3.195 Incomplete Line

A sequence of one or more non- <newline> characters at the end of the file.

The general idea is that text file can be treated as a list of records, where every record is terminated by \n. In other words, \n is not something between lines - it is the part of the line. See for example the fgets() function: the \n is always included and serves to identify the case whether the text line was read completely or not. If the last line is missing the \n, then one has to do more checks to read the file correctly.

In general, as long as your text files are created on *NIX by *NIX programs/scripts, it is fine to expect that last line is properly terminated. But many Java applications as well as the Windows applications do not handle that correctly or consistently. Not only they often forget to add the last \n, oftentimes they also incorrectly treat the trailing \n as an additional empty line.