标题中的 git 是一个动词,标题的意思是可以在任意路径下,对想操作的 git 库文件夹操作
问题:假设有一天,需要在 ~ 目录下对 /mnt/test 进行 git 操作,无论是需要 pull 还是 push,又或者是其他的什么操作
看到这个问题,想当然的大概就会选择 cd 过去,那么如果在不能 cd 的情况下,要怎么办?
这或许不是个值得思考的问题,但是 git 的作者也给出了对应的答案,那就是 git 的两个选项 git-dir 和 work-tree
以下是用这两个选项完成一次文件的提交的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| $ pwd /Users/test
$ ls -a /mnt/test/ . .. .git 1.txt 2.txt
$ git --git-dir=/mnt/test/.git --work-tree=/mnt/test log --oneline 10b6650 (HEAD -> master) add 2.txt 73c8622 add 1.txt
$ echo 3 > /mnt/test/3.txt $ git --git-dir=/mnt/test/.git --work-tree=/mnt/test status 位于分支 master 未跟踪的文件: (使用 "git add <文件>..." 以包含要提交的内容) 3.txt
提交为空,但是存在尚未跟踪的文件(使用 "git add" 建立跟踪)
$ git --git-dir=/mnt/test/.git --work-tree=/mnt/test add 3.txt $ git --git-dir=/mnt/test/.git --work-tree=/mnt/test status 位于分支 master 要提交的变更: (使用 "git restore --staged <文件>..." 以取消暂存) 新文件: 3.txt
$ git --git-dir=/mnt/test/.git --work-tree=/mnt/test commit -m 'add 3.txt' [master b3cedfe] add 3.txt 1 file changed, 1 insertion(+) create mode 100644 3.txt $ git --git-dir=/mnt/test/.git --work-tree=/mnt/test status 位于分支 master 无文件要提交,干净的工作区
|
此外,需要注意的是,~ 作为 home 目录在这两个选项中并不能使用,但是相对路径则没有问题
但是如果这两个选项仅仅用来这个用途,那好像是有点大材小用了,毕竟 cd 更香,所以,来了来了,它来了
如果想将 /mnt/test/ 中的指定 commit 的某些文件 copy 到其他目录中,该怎么办?clone 以后通过 checkout 当然是一个可行的方法,但如果库比较大,clone 就显得不是很合适,这时候就可以考虑使用 git checkout 命令来实现,只需显式指定 work-tree 即可
以下是把 /mnt/test/ 的 master 分支处于 HEAD 的文件复制到 /Users/test/git_test/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| $ pwd /mnt/test
$ git --work-tree=/Users/test/git_test/ status 位于分支 master 尚未暂存以备提交的变更: (使用 "git add/rm <文件>..." 更新要提交的内容) (使用 "git restore <文件>..." 丢弃工作区的改动) 删除: 1.txt 删除: 2.txt 删除: 3.txt
修改尚未加入提交(使用 "git add" 和/或 "git commit -a")
$ git --work-tree=/Users/test/git_test/ checkout HEAD . 从 7eab585 更新了 3 个路径 $ git --work-tree=/Users/test/git_test/ status 位于分支 master 无文件要提交,干净的工作区 $ ls -a /Users/test/git_test . .. 1.txt 2.txt 3.txt
|
为了和当前目录的文件进行区分操作,建议先创建一个分支,方便对另一个目录的文件进行操作,完成后,在本目录中将分支切换回来,避免对目录文件产生影响
be slow to promise and quick to perform.