Re: sh read on files missing the final newline

Rhialto <[email protected]> Mon, 6 Jul 2026 18:48:39 +0200
Newsgroups gmane.os.netbsd.devel.userlevel
Message-ID <[email protected]>
--8dvaL+yL2GRhyIPu
Content-Type: text/plain; charset=iso-8859-1
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Mon 06 Jul 2026 at 18:27:01 +0200, Edgar Fu=DF wrote:
> I stumbled over the fact that sh's read returned 1 on the final part=20
> (call it a line or not) of a file when it didn't end in a newline.
>=20
> Digging through SUS revealed (in the informative part of read):
>=20
> 	Although the standard input is required to be a text file, and=20
> 	therefore will always end with a <newline> (unless it is an empty file)
>=20
> as well as other passages that suggested that a "text file" consists of=
=20
> "lines" and a "line" is a sequence of non-newline characters plus a newli=
ne,=20
> but I couldn't find a definition explicitly stating that.

K&R Second Edition (mine is "Based on Draft-Proposed ANSI C") says on
page 15, para 1.5 "Character Input and Output":

A /text stream/ is a sequence of characters divided into lines; each
line consists of zero or more characters followed by a newline
character.

but then also, next:

It is the responsibility of the library to make each input or output
stream conform to this model; the C programmer using the library need
not worry about how lines are represented outside the program.

So in theory the library has the option to convert trailing garbage into
a line by appending a newline. Or it can declare that a file not ending
in a newline does not represent a text stream and refuse to open it. But
the program has to ignore any garbage that doesn't end with a newline,
too.

-Olaf.
--=20
___ Olaf 'Rhialto' Seibert                            <rhialto/at/falu.nl>
\X/ There is no AI. There is just someone else's work.           --I. Rose

--8dvaL+yL2GRhyIPu
Content-Type: application/pgp-signature; name=signature.asc

-----BEGIN PGP SIGNATURE-----

iQFPBAEBCAA5FiEEFVAhiiWjqgwBVdQAmYnGRWHD+9MFAmpL3GIbFIAAAAAABAAO
bWFudTIsMi41KzEuMTIsMiwzAAoJEJmJxkVhw/vTEd8H+gO5eUs1O3arZ38yPMSZ
sN/nUWewAP3b96dW6LGu2SheKiQLowvNB7xhX0ZZTWChxwjPLi51M1ysm5FAMZUw
Dc7akh0raaRZEkAOtxOrnNS8ahypjoakxpk+Y7gqU6eLLWLbYfU7rCEY+jUK8/Jv
rXqVjtF3xDEuvBw1XkEByVglnBAvqrj0+cgSHjrct7RFQVUKf92hYDCjbonvDYqM
m7oKUZMYQIfPVDPHwgSPTcFApNe/z7j9ndzyhL46Ui+H5d6sSXvRz/IpCVCu4kMs
P+itNyX28NCHwOeX3tk5ytWgm5Hi0rkHkEQIZegShFqtX9mNBGN1QXgjqWHsP0IE
vHQ=
=z1Gu
-----END PGP SIGNATURE-----

--8dvaL+yL2GRhyIPu--