FreeKB - Roll back to a prior version of a file in Git
Roll back to a prior version of a file in Git

Home > Search


If you are not familiar with Git, check out our getting started article. These examples are based on Linux. Let's say you've added and commited example.txt in Git, and example.txt contains the following.

Foo

 

Then you replaced Foo with Bar, and commited example.txt. Now, you want to roll back example.txt, so that example.txt again contains Foo.

Bar

 

The git log will show both commits and provide you with the commit ID.

afba75a Bar
741785c Foo

 

The git show command can be used to confirm that the file had Foo at first commit and Bar at second commit.

It's a good idea to use git stash, in case example.txt in your local Git repository (branch) has commits that have not been push to the master Git repository (trunk).

git stash

 

You can use the git revert command to roll back to a prior commit. git revert HEAD will revert to the prior commit. This will revert example.txt back so that it contains Foo.

git revert HEAD

 

Or, you can specify a specific commit using the commit ID, with the exception of the very first commit.

git revert afba75a

 

By default, your default editor will open and you will be prompted to enter the commit message. You may want to use the --no-edit option to bypass this prompt.

git revert --no-edit afba75a

 

If the revert is successful, the following should be displayed.

x files changed, x insertions(+), x deletion(-)

 

Likewise, the git log will contain a new commit ID followed by keyword Revert, and your commit message. Notice that this means that revert also does a commit, thus there is no need to do a commit.

97d7432 Revert "Bar"

 

Don't forget to push the file from your local Git repository (branch) to the master Git repository (trunk).



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter 86a0f in the box below so that we can be sure you are a human.




Comments