乐闻世界logo
搜索文章和话题

How do I discard unstaged changes in Git?

1个答案

1

In Git, if you want to discard unstaged changes, there are several methods you can use.

  1. Using the git checkout command: The most straightforward approach is to use the git checkout command, which restores the file to the state of the last commit. For example, to discard all unstaged changes for the file example.txt, run:
sh
git checkout -- example.txt

This command restores the example.txt file to the state of the last commit.

  1. Using the git restore command:

Starting from Git 2.23, the git restore command provides a more intuitive way to handle restoration. If you simply want to discard unstaged changes for a specific file, use:

sh
git restore example.txt

This will also restore example.txt to the state of the last commit.

  1. For all unstaged changes:

To discard unstaged changes across all files, you can use:

sh
git checkout -- .

Alternatively, use the git restore command:

sh
git restore .

Both commands restore all files in the working directory to the state of the last commit.

  1. Using git clean to remove untracked files:

If your directory contains untracked files (i.e., newly added files not yet tracked by Git), the above commands do not handle these files. To remove untracked files, use:

sh
git clean -f

This command deletes all untracked files. If untracked directories exist, include the -d option:

sh
git clean -fd

By using these methods, you can select the appropriate command based on your needs to manage unstaged changes in Git. In practical work, correctly applying these commands helps maintain a clean working directory and avoids issues caused by incorrect changes.

2024年8月8日 05:42 回复

你的答案