0

For revert the changes to a file in a commit, from https://stackoverflow.com/a/2620822/156458

#!/bin/bash

function output_help {
    echo "usage: git-revert-single-file <sha1> <file>"
}

sha1=$1
file=$2

if [[ $sha1 ]]; then
git diff $sha1..$sha1^ -- $file | patch -p1
else
output_help
fi

Why is -p1 to patch in

git diff $sha1..$sha1^ -- $file | patch -p1

Thanks.

3

Because git diff adds fake directories a and b to its patches, which need to be skipped by patch (hence the -p1). git does this to represent information that’s not in the file system (the files being compared don’t exist simultaneously); for example

diff --git a/README b/README
index ce01362..a1e6cf9 100644
--- a/README
+++ b/README
@@ -1 +1,2 @@
 hello
+Tim

for a README file in the current directory. diff would produce

--- README.orig 2017-04-07 20:39:50.843962430 +0200
+++ README      2017-04-07 20:39:56.284108455 +0200
@@ -1 +1,2 @@
 hello
+Tim

(assuming we’ve kept a copy of the original elsewhere); note the absence of directories here (since the files are in the current directory).

The latter patch applies as-is with patch; the former needs to have the first element of each path stripped, hence the -p1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.