Git·30 questions

How to roll back changes in a specific file to the state of a certain commit?

Answer

Sometimes during the development process, there is a need to return one or more files to the state they were in the past, without affecting other changes in the project. The Git version control system allows you to manage file history granularly without having to perform a global rollback of the entire repository or lose current progress.

The easiest way to retrieve an old version of a file from history is to use the git checkout command or the modern git restore. To replace a file in the current working directory with its version from a specific commit, you need to run the git checkout command specifying the commit hash and the path to the desired file. This will overwrite the file's contents with up-to-date data from the past.

After running this command, the file will automatically end up in the working area as modified, and you will be able to see the difference using git diff. If you want to commit this state immediately, the file needs to be added to the staging area again via git add and a new commit made to record the return to the old code.

This approach is extremely convenient for restoring accidentally deleted or corrupted files when you know for sure what working state they were in previously. The main thing is to make sure you specified the correct commit hash so as not to confuse versions and not lose important intermediate project developments.

Was this answer helpful?

More questions in this topic

Related questions from other topics