Determine whether a file has no EOL at the end from the command line

command linefilesnewlines

If you open a file in vim and that file has no EOL at the end of its last line, then the editor will report it as [noeol]. How can I determine this before opening it in vim? (Is there a command I can issue to determine this?)

Best Answer

tail -c 1 outputs the last character (more precisely, the last byte) of its input.

Command substitution strips off a trailing newline, so $(tail -c 1 <…) is empty if the last character of the file is a newline. It's also empty if the last character is a null byte (in most shells), but text files don't have null bytes.

Keep in mind that an empty file doesn't need an extra newline.

if [ ! -s "$filename" ]; then
  echo "$filename is empty"
elif [ -z "$(tail -c 1 <"$filename")" ]; then
  echo "$filename ends with a newline or with a null byte"
else
  echo "$filename does not end with a newline nor with a null byte"
fi