Git 跟踪的任何文件的内容都可以从暂存区域或提交中还原。

您可以取消阶段性更改,以便这些更改不会包含在下一次提交中。本章说明如何执行此操作。

从暂存区域中删除暂存更改

使用该命令从暂存区域中删除暂存更改。这样可以避免在下一次提交中包含这些更改。git reset [paths]

这意味着 这与 相反。这些更改在工作树中仍然可用,您可以稍后暂存并提交它们。git reset [paths]git add [paths]

在下面的示例中,您将创建一个新文件并更改现有文件。这两项更改都是分阶段进行的。

# do changes
touch unwantedstaged.txt
echo "more.." >> test02

// add changes to staging area
git add unwantedstaged.txt
git add test02

# see the status
git status
该命令的输出应类似于以下内容。git status

On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    modified:   test02
    new file:   unwantedstaged.txt

使用以下命令从暂存区域中删除更改。

# remove test02 from the staging area
git reset test02

# remove unwantedstaged.txt from the staging area
git reset unwantedstaged.txt

使用该命令查看结果。git status

On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   test02

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    unwantedstaged.txt

no changes added to commit (use "git add" and/or "git commit -a")

的行为因您提供的选项而异。git reset

删除工作树中的更改

请谨慎使用以下命令。它允许您覆盖工作树中文件中的更改。您将无法还原这些更改。

工作树中未暂存的不需要的更改可以使用该命令撤消。此命令将工作树中的文件重置为最新的暂存版本。如果没有暂存更改,则使用最新提交的版本进行还原操作。git checkout

# delete a file
rm test01

# revert the deletion
git checkout -- test01

# note git checkout test01 also works but using
# two - ensures that Git understands that test01
# is a path and not a parameter

# change a file
echo "override" > test01

# restore the file
git checkout -- test01

例如,可以还原使用以下命令调用的目录的内容。data

git checkout -- data

删除工作树和暂存区域中的更改

如果要撤消暂存但未提交的更改,请使用该命令。此版本的命令将重置工作树和暂存区域。git checkout [commit-pointer] [paths]

下面演示了如何使用它来还原已删除的目录。

# create a demo directory
mkdir checkoutheaddemo
touch checkoutheaddemo/myfile
git add .
git commit -m "Adds new directory"

# now delete the directory and add the change to
# the staging area
rm -rf checkoutheaddemo
# Use git add . -A for Git version < 2.0
git add .

# restore the working tree and reset the staging area
git checkout HEAD -- checkoutheaddemo

附加的 commit 指针参数指示命令重置工作树并删除暂存的更改。git checkout

根据上次提交更改删除暂存区域

将文件的更改添加到暂存区域后,还可以根据上次提交还原暂存区域中的更改。

# some nonsense change
echo "change which should be removed later" > test01

# add the file to the staging area
git add test01

# restores the file based on HEAD in the staging area
git reset HEAD test01
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐