# 创建 lab 文件夹
$ mkdir lab
# 移动文件到lab目录
$ git mv test.txt lab
# 查看 Git 状态
$ git status
On branch master
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
renamed: test.txt -> lab/test.txt
# 提交更改
$ git commit -m "Moved test.txt to lab"
[master 40e4259] Moved test.txt to lab
1 file changed, 0 insertions(+), 0 deletions(-)
rename test.txt => lab/test.txt (100%)
# 查看提交记录
$ git hist
* d84d6fa 2023-05-05 | Moved test.txt to lab (HEAD -> master) [aku]
* 929f644 2023-05-05 | Added 123456 to the test.txt [aku]
* d7f681f 2023-05-05 | Added abc to the test.txt (tag: v1) [aku]
* 01b8702 2023-05-05 | Add first file (tag: v1-beta) [aku]
# 查看提交日志
$ git hist
* 40e4259 2023-05-05 | Moved test.txt to lab (HEAD -> master) [aku]
* 929f644 2023-05-05 | Added 123456 to the test.txt [aku]
* d7f681f 2023-05-05 | Added abc to the test.txt (tag: v1) [aku]
* 01b8702 2023-05-05 | Add first file (tag: v1-beta) [aku]
# 复制移动前的提交哈希值并重置
$ git reset --hard 929f644
HEAD is now at 929f644 Added 123456 to the test.txt
# 查看提交历史
$ git hist
* 929f644 2023-05-05 | Added 123456 to the test.txt (HEAD -> master) [aku]
* d7f681f 2023-05-05 | Added abc to the test.txt (tag: v1) [aku]
* 01b8702 2023-05-05 | Add first file (tag: v1-beta) [aku]
# 创建 lab 文件夹
$ mkdir lab
# 移动文件到lab目录
$ mv test.txt lab
# 查看 Git 状态
$ git status
On branch master
Changes not staged for commit:
(use "git add/rm <file>..." to update what will be committed)
deleted: test.txt
Untracked files:
(use "git add <file>..." to include in what will be committed)
lab/
no changes added to commit (use "git add" and/or "git commit -a")
#暂存
$ git add lab
# 删除文件
$ git rm test.txt
rm 'test.txt'
# 查看 Git 状态
$ git status
On branch master
(use "git restore --staged <file>..." to unstage)
renamed: test.txt -> lab/test.txt
# 暂存
$ git add .\lab\test.txt
# 提交
$ git commit -m "Moved test.txt to lab"
[master f40c829] Moved test.txt to lab
1 file changed, 0 insertions(+), 0 deletions(-)
rename test.txt => lab/test.txt (100%)
# 查看提交历史
$ git hist
* b77158a 2023-05-05 | Moved test.txt to lab (HEAD -> master) [aku]
* 929f644 2023-05-05 | Added 123456 to the test.txt [aku]
* d7f681f 2023-05-05 | Added abc to the test.txt (tag: v1) [aku]
* 01b8702 2023-05-05 | Add first file (tag: v1-beta) [aku]
当使用操作系统命令移动或重命名文件时,Git 无法识别这个操作,它只会看到一个文件被删除而另一个文件被创建。这意味着 Git 不知道这两个文件之间的关系,并且将新文件视为一个全新的文件。因此,在这种情况下,如果您要跟踪重命名或移动文件的历史记录,则需要手动告诉 Git 文件已经被移动。
相反,如果您使用 Git 命令来移动或重命名文件,Git 将会记录这个操作并且可以正确地跟踪文件的历史记录。具体来说,您可以使用以下 Git 命令来移动或重命名文件:
在 Git 中,重命名和移动文件的实现方式是相同的:Git 实际上并不对文件进行移动或重命名操作,而是将旧文件标记为已删除,并将新文件标记为新添加的文件。然后,Git 在提交历史记录中跟踪这些更改,并通过查看文件内容的相似性来确定哪些文件已被重命名或移动。
# 重命名一个文件
$ git mv .\lab\test.txt .\lab\abc.txt
$ git status
On branch master
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
renamed: lab/test.txt -> lab/abc.txt
# 未提交的状态下,再次执行 git mv 恢复
$ git mv .\lab\abc.txt .\lab\test.txt
$ git status
On branch master
nothing to commit, working tree clean