我如何(快速)判断 $PWD 是否在 git/hg 存储库中?
我想测试我当前的目录是否是 git/hg/etc 的一部分。存储库,作为我的 shell 提示符的一部分。搜索了一下,我发现这个设置有类似的测试我想要的。所以我想我的问题是:最快的测试是什么来查看我是否在 git、hg、darcs 或 svn 存储库中?特别是,在我给出的链接中,他使用 gitbranch>; /dev/null
和 hg root > /dev/null
;这些是最快的吗?
I want to test if my present directory is part of a git/hg/etc. repository, as part of my shell prompt. Searching around a bit, I found this setup which has similar tests to what I want. And so I guess my question is: what are the fastest tests to see if I am in a git, hg, darcs, or svn repository? In particular, in the link I gave he uses git branch > /dev/null
and hg root > /dev/null
; are those the fastest?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您确实需要性能,可以检查
.git
或.hg
目录。但这当然不会100%可靠。If you really need performance, you could check for
.git
or.hg
directories. But this of course is not going to be 100% reliable.测试
.git
、.hg
等是否存在是一个非常好的近似值(对于提示来说绝对足够好)。但你不能只在当前目录中测试,你还需要检查父目录。以下(未经测试的)bash/ksh/zsh 片段将 vc 设置为当前目录所在的版本控制系统,如果找不到,则设置为空字符串。Testing for the existence of
.git
,.hg
and so on is a very good approximation (definitely good enough for a prompt). But you can't just test in the current directory, you need to check parent directories as well. The following (untested) bash/ksh/zsh snippet setsvc
to the version control system the current directory appears to be under, or to the empty string if it can't find one.早上,我有这个可怕的作品,因为我不记得了。
给出:
可能不适合您,正如您在提示中所希望的那样。 (我讨厌超载我的提示:)
morning, I had this terrible piece, because I could not remember.
gives:
Might not be for you, as you want it in the prompt. (I hate overloading my prompt :)
如果你看看 git 做了什么,它可能是最简单的(无需编写)、最快的(用 C 编写的)和最可靠的方式(你使用的是官方算法)。
简而言之 'gitbranch 2>/dev/null' 是要走的路。
从 git 工作目录:
从非 git 目录:
IMO git-show 应该提供一种反思给定存储库和工作目录的方法,因为 GIT_WORK_TREE 和 GIT_DIR 是如何工作的。
If you look at what git does, it's probably the simplest (nothing to write), fastest (it's written in C) and surest way (you're using the official algorithm).
In short 'git branch 2>/dev/null' is the way to go.
From a git working directory:
From a non-git directory:
IMO git-show should provide a way to introspect about the given repository and working directory, because of how GIT_WORK_TREE and GIT_DIR work.
不知道这对你是否有帮助,但这是我的 PS1 for git 存储库:
是的,在每次目录更改时调用“git 分支”有点疯狂,但我已经使用它很多年了,没有任何问题。 :-)
Don't know if it will be helpful for you but here is my PS1 for git repository:
Yes, it's a bit crazy to call 'git branch' on every directory change but I've been living with that for ages without a problem. :-)