当您在某个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 ls-remote --get-url | xargs basename -s .git # bar

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

其他回答

如果你试图获得用户名或组织名称和github上的项目或回购名称,我能够编写这个命令,至少在本地为我工作。

▶ git config --get remote.origin.url
# => https://github.com/Vydia/gourami.git

▶ git config --get remote.origin.url | sed 's/.*\/\([^ ]*\/[^.]*\).*/\1/' # Capture last 2 path segments before the dot in .git
# => Vydia/gourami

这是理想的结果,因为Vydia是组织名称,而gourami是包名称。它们组合在一起可以帮助形成完整的用户/回购路径

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

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不关心你的Git存储库是如何命名的。例如,你可以重命名包含你的存储库的目录(一个带有.git子目录的目录),git甚至不会注意到它——一切都将继续工作。

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

git remote show origin

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

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

这种使用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