In managing projects with Git, restoring changes to the working directory is a common need. Several methods exist for restoring changes, and the choice depends on the desired state and the current working environment. I will introduce several common methods for restoring changes.
1. Using git checkout
If you want to discard changes to a specific file, you can use the git checkout command. This command restores the file to the state of the last commit.
Example:
Suppose you modified a file named example.txt and want to undo these changes. You can run:
bashgit checkout -- example.txt
This restores example.txt to the state of the last commit.
2. Using git restore
Starting from Git 2.23, you can use the git restore command for more convenient file restoration. This command has a clearer purpose and more intuitive semantics.
Example:
If you modified example.txt and want to undo the changes, you can run:
bashgit restore example.txt
This restores example.txt to the state of the last commit. To restore the entire working directory, you can use:
bashgit restore .
3. Using git reset
If you want to discard all unstaged changes, you can use the git reset command. This command discards all local changes since the last commit.
Example:
bashgit reset --hard
This resets the current branch head to the last commit, discarding all changes.
4. Using git clean
If you have untracked files or directories in your working directory, you can use git clean to remove them.
Example:
bashgit clean -fd
Here, -f means force, and -d means also delete untracked directories. This command removes all untracked files and directories.
Summary
The choice depends on your specific needs. If you only want to discard changes to a specific file, using git checkout or git restore is sufficient. If you need to discard all changes and return to a specific commit state, use git reset --hard. If you also need to handle untracked files and directories, git clean is a good choice. In practice, these commands are very useful for managing and restoring code states.