当您在某个Git目录下工作时,如何获得某个Git存储库中的Git存储库名称?有Git命令吗?

# I did check out bar repository and working in somewhere 
# under bar directory at this moment such as below.

$ git clone git://github.com/foo/bar.git
$ cd bar/baz/qux/quux/corge/grault # and I am working in here!
$ git xxx # <- ???
bar

当前回答

一般来说,你不能这样做。Git不关心你的Git存储库是如何命名的。例如,你可以重命名包含你的存储库的目录(一个带有.git子目录的目录),git甚至不会注意到它——一切都将继续工作。

但是,如果你克隆了它,你可以使用命令:

git remote show origin

来显示关于您从其克隆存储库的原始远程的大量信息,并且它将包含原始克隆URL。

但是,如果您使用git remote rm origin删除了到原始远程的链接,或者如果您使用git init创建了该存储库,则这些信息根本不可能获得——它不存在于任何地方。

其他回答

现在问这个问题有点晚了,但如果你:

cat /path/to/repo/.git/config

你将看到存储库的url,其中包括reponame:

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    ignorecase = true
    precomposeunicode = true
[remote "origin"]
    url = https://github.com/your_git_user_name/your_git_repo_name.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master

这种使用git-remote的方法对我来说很有效,适用于HTTPS遥控器:

$ git remote -v | grep "(fetch)" | sed 's/.*\/\([^ ]*\)\/.*/\1/'
                                                |  |        | |
                                                |  |        | +---------------+
                                                |  |        | Extract capture |
                                                |  +--------------------+-----+
                                                |Repository name capture|
                                                +-----------------------+

例子

git ls-remote --get-url | xargs basename -s .git # bar

# zsh
git ls-remote --get-url | read
print $REPLY:t:r # bar

回购全称:

git config --get remote.origin.url | grep -Po "(?<=git@github\.com:)(.*?)(?=.git)"

如果你想要整个GitHub存储库名称('全名')-用户/存储库,并且你想用Ruby实现它…

git remote show origin -n | ruby -ne 'puts /^\s*Fetch.*:(.*).git/.match($_)[1] rescue nil'