Over at Can you modify text files when committing to subversion? Grant suggested that I block commits instead.
However I don't know how to check a file ends with a newline. How can you detect that the file ends with a newline?
use a text editor like notepad++ that can help you with understanding the line ends. It will show you the line end formats used as either Unix(LF) or Macintosh(CR) or Windows(CR LF) on the task bar of the tool. you can also go to View->Show Symbol->Show End Of Line to display the line ends as LF/ CR LF/CR.
Try file -k Short version: file -k somefile. txt will tell you. It will output with CRLF line endings for DOS/Windows line endings. It will output with CR line endings for MAC line endings.
So, it turns out that, according to POSIX, every text file (including Ruby and JavaScript source files) should end with a \n , or “newline” (not “a new line”) character. This acts as the eol , or the “end of line” character. It is a line “terminator”.
@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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With