bash 检查目录是否是 git 存储库(无需 cd 进入)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39518124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if directory is git repository (without having to cd into it)
提问by Ataraxia
What's a shell command I can use to, using the full directory path, determine whether or not a given directory is a git repository? Specifically, I'd like to be able to do this without being in the directory, and without having to cd into it. I'd also like to be able to do it with a command that returns a simple "true" or "false" (much the way that rev-parse --is-inside-work-tree does), but it's not a requirement.
什么是 shell 命令,我可以使用完整目录路径来确定给定目录是否是 git 存储库?具体来说,我希望能够在不进入目录的情况下执行此操作,而无需 cd 进入该目录。我还希望能够使用返回一个简单的“真”或“假”的命令来做到这一点(就像 rev-parse --is-inside-work-tree 所做的那样),但这不是必需的.
回答by ypnos
Use git -C <path> rev-parse
. It will return 0 if the directory at <path>
is a git repository and an error code otherwise.
使用git -C <path> rev-parse
. 如果目录 at<path>
是 git 存储库,它将返回 0,否则返回错误代码。
回答by Simon Clarkstone
Any directory in the system could be a git working copy. You can use an directory as if it contained a .git
subdirectory by setting the GIT_DIR
and GIT_WORK_TREE
environment variables to point at an actual .git
directory and the root of your working copy, or use the --git-dir
and --work-tree
options instead. See the git man pagefor more details.
系统中的任何目录都可以是 git 工作副本。.git
通过将GIT_DIR
和GIT_WORK_TREE
环境变量设置为指向实际.git
目录和工作副本的根目录,您可以使用目录,就像它包含子目录一样,或者改用--git-dir
and--work-tree
选项。有关更多详细信息,请参阅git 手册页。
回答by Walk
We can also try git status
command and if the output is like :
我们也可以尝试git status
命令,如果输出是这样的:
fatal: Not a git repository (or any of the parent directories): .git
fatal: Not a git repository (or any of the parent directories): .git
Then, the directory is not a git repository.
然后,该目录不是 git 存储库。
回答by user3108793
Adding to @Walk's comments,
git status
will throw fatal message if its not a repo.
echo $?
will help to capture of its an ERROR or not.
If its a git repo then echo $?
will be 0 else 128 will be the value
添加到@Walk 的评论中,git status
如果它不是 repo ,
将抛出致命消息。
echo $?
将有助于捕获其错误与否。如果它是一个 git repo 那么echo $?
它将是 0 否则 128 将是值