What does 'patch unexpectedly ends in middle of line' mean?

This is the output of my patch command:

Hunk #11 merged at 4184,4190.
Hunk #12 merged at 4444.
Hunk #13 merged at 4944.
Hunk #14 NOT MERGED at 5106-5116.
Hunk #15 merged at 5290.
Hunk #16 merged at 5448.
patch unexpectedly ends in middle of line
Hunk #17 merged at 5608,5611.

The command was

patch -d ~/SOME_DIR -p1 --merge --verbose -u

The patch was produced using git:

git --git-dir ~/SOME_DIR/.git diff -U8 bb1ee538982957b421a4c0e78f30428e73c9a072 HEAD -- malloc.c

What does patch unexpectedly ends in middle of line mean, and is it a problem? Is it referring to hunk 16 or 17? What can I look for in the patch file to figure out what’s causing this?

Asked By: Paul Biggar

||

The message refers to Hunk 16.

This GitHub discussion is probably related to your issue.

It is about patch unexpectedly ends in middle of line messages because of CRLF (carriage-return, linefeed) issues when git generated diffs are used with patch.

To quote the conclusion:

[..] git can be very picky about line endings. Are you on windows or not? At any rate, you should probably set autocrlf in the git config. If you’re on windows, you want “true”, if you’re on mac or linux, you should use “input” [..]

In the article Dealing with line endings GitHub details the above statement.

Answered By: maxschlepzig

If you’re not using git (@maxslepzig’s comment was about using patch in the context of git), try adding a carriage return at the end of your file. I did that and patch accepted my patch.

Answered By: Son of the Wai-Pan

To add to this very old discussion:

The problem leading to the warning the OP noted is generally caused by problems with line endings.

patch wants a trailing line feed (LF) in order to determine the end of file (and warns of a unified diff that may have been accidentally truncated)

  1. Append the proper linefeed without opening the file up for editing (which might modify your line endings or strip trailing lines/spaces depending on your editor’s settings) you can do something simple like:

    echo -e "n" >> YOURPATCHFILE

    This appends a linefeed character to the end of the file without making any other changes.

  2. If your patch file is already weird or you want to go through several possible fixes at once, you can correct many problems with encoding (to ascii) including the line endings (CR or CRLF to LF):

    dos2unix -k YOURPATCHFILE

    You may have to install the dos2unix binary from your OS’s package manager; i.e.

    • Debian/Ubuntu based: sudo apt install dos2unix
    • Fedora/RHEL/CentOS: sudo yum install dos2unix
    • MacOS (with brew): brew install dos2unix
Answered By: ChrisN
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.