Appending a new line to a file, checking whether last character is a newline character or not in Bash

bash

Solution

You can use:

x=$(tail -c 1 aFile.txt)
if [ "$x" != "" ]
then echo >> aFile.txt
fi
echo "some line of text" >> aFile.txt

The `$(...)` operator removes the trailing newline from the output of the command embedded in it, and the `tail -c 1` command prints the last character of the file. If the last character is not a newline, then the string `"$x"` won't be empty, so append a newline to the file before appending the new line of text.

Problem

I wanted to append a new line to the end of a file, but some of the files I'm working with may not contain newline characters as their last character, which means I'm appending onto the same line. Is there an easy way to check for newline characters, and adjust accordingly? `echo "some line of text" >> aFile.txt`

Original source