Linux - check if there is an empty line at the end of a file

I found the solution here.

#!/bin/bash
x=`tail -n 1 "$1"`
if [ "$x" == "" ]; then
    echo "Newline at end of file!"
else
    echo "No Newline at end of file!"
fi

IMPORTANT: Make sure that you have the right to execute and read the script! chmod 555 script

USAGE:

./script text_with_newline        OUTPUT: Newline at end of file!
./script text_without_newline     OUTPUT: No Newline at end of file!

Just type:

cat -e nameofyourfile

If there is a newline it will end with $ symbol. If not, it will end with a % symbol.


Olivier Pirson's answer is neater than the one I posted here originally (it also handles empty files correctly). I edited my solution to match his.

In bash:

newline_at_eof()
{
    if [[ -s "$1" && -z "$(tail -c 1 "$1")" ]]
    then
        echo "Newline at end of file!"
    else
        echo "No newline at end of file!"
    fi
}

As a shell script that you can call (paste it into a file, chmod +x <filename> to make it executable):

#!/bin/bash
if [[ -s "$1" && -z "$(tail -c 1 "$1")" ]]
then
    echo "Newline at end of file!"
else
    echo "No newline at end of file!"
fi

The \Z meta-character means the absolute end of the string.

if (preg_match('#\n\Z#', file_get_contents('foo.txt'))) {
    echo 'New line found at the end';
}

So here you are looking at a new line at the absolute end of the string. file_get_contents will not add anything at the end. BUT it will load the entire file into memory; if your file is not too big, its okay, otherwise you'll have to bring a new solution to your problem.