You can use git checkout command to restore/revert a file to an older version using the previous git commit.
Example:
Create a new git local repository:
1 2 |
## Create a new git local repository git init myrepo && cd myrepo |
Create a file and add some changes each time committing them:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
## Create first commit echo "cat" > file1 git add file1 git commit -m "commit1" ## Create second commit echo "dog" >> file1 echo "bat" > file2 git add . git commit -m "commit2" ## Create third commit echo "cow" >> file1 echo "snake" >> file2 git add . git commit -m "commit3" |
Check the current content of the file and git log:
1 2 3 4 5 6 7 8 |
## current version of file2 cat file2 ## returns bat and snake ## get git sha for previous commit (commit2) git log --oneline ## 43547ea (HEAD -> master) commit3 ## 1ed0e7b commit2 ## e443913 commit1 |
Restore file from previous commit in git:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
## restore file2 from "commit2" git checkout 1ed0e7b -- file2 ## restored version of file2 cat file2 ## returns bat ## current version of file1 cat file1 ## returns cat, dog and cow ## restore file1 from "commit1" git checkout e443913 -- file1 ## restored version of file1 cat file1 ## returns cat ## add and commit the restored version git commit -am "commit4" ## delete the repository cd .. && rm -rf myrepo |