Revert changes to a file in a commit

后端 未结 8 1935
無奈伤痛
無奈伤痛 2020-12-12 09:45

I want to revert changes made by a particular commit to a given file only.

Can I use git revert command for that?

Any other simple way to do it?

相关标签:
8条回答
  • 2020-12-12 10:22

    You can follow this procedure:

    1. git revert -n <*commit*> (-n revert all the changes but won't commit them)
    2. git add <*filename*> (name of the file/s you want to revert & commit)
    3. git commit -m 'reverted message' (add a message for reverting)
    4. after committing discard the other files changes so the files stay updated with the changes you committed before the revert
    0 讨论(0)
  • 2020-12-12 10:25

    git revert is for all file contents within a commits.

    For a single file, you can script it:

    #!/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
    

    (From the git-shell-scripts utilities from smtlaissezfaire)


    Note:

    another way is described here if you have yet to commit your current modification.

    git checkout -- filename
    

    git checkout has some options for a file, modifying the file from HEAD, overwriting your change.


    Dropped.on.Caprica mentions in the comments:

    You can add an alias to git so you can do git revert-file <hash> <file-loc> and have that specific file be reverted.
    See this gist.

    [alias]
      revert-file = !sh /home/some-user/git-file-revert.sh
    
    0 讨论(0)
提交回复
热议问题