How to detect file ends in newline?

@Konrad: tail does not return an empty line. I made a file that has some text that doesn't end in newline and a file that does. Here is the output from tail:

$ cat test_no_newline.txt
this file doesn't end in newline$ 

$ cat test_with_newline.txt
this file ends in newline
$

Though I found that tail has get last byte option. So I modified your script to:

#!/bin/sh
c=`tail -c 1 $1`
if [ "$c" != "" ]; then
    echo "no newline"
fi

Or even simpler:

#!/bin/sh
test "$(tail -c 1 "$1")" && echo "no newline at eof: '$1'"

But if you want a more robust check:

test "$(tail -c 1 "$1" | wc -l)" -eq 0 && echo "no newline at eof: '$1'"

Here is a useful bash function:

function file_ends_with_newline() {
    [[ $(tail -c1 "$1" | wc -l) -gt 0 ]]
}

You can use it like:

if ! file_ends_with_newline myfile.txt
then
    echo "" >> myfile.txt
fi
# continue with other stuff that assumes myfile.txt ends with a newline