当您在某个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 remote -v

文档: https://git-scm.com/docs/git-remote

管理您跟踪其分支的存储库集(“远程”)。 - v 更详细一点,在名称后显示远程url。注意:这个必须放在remote和subcommand之间。

其他回答

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

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

git remote show origin

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

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

这是我的:

git remote --verbose | grep origin | grep fetch | cut -f2 | cut -d' ' -f1

没有比其他的更好,但我把它作为一个bash函数,所以如果它不是origin,我可以在远程名称中删除。

grurl () {
  xx_remote=$1
  [ -z "$xx_remote" ] && xx_remote=origin
  git remote --verbose | grep "$1" | grep fetch | cut -f2 | cut -d' ' -f1
  unset xx_remote
}

下面是一个bash函数,它将打印存储库名称(如果它已经正确设置):

__get_reponame ()
{
    local gitdir=$(git rev-parse --git-dir)

    if [ $(cat ${gitdir}/description) != "Unnamed repository; edit this file 'description' to name the repository." ]; then
        cat ${gitdir}/description
    else
        echo "Unnamed repository!"
    fi
}

解释:

local gitdir=$(git rev-parse --git-dir)

这将执行git rev-parse——git-dir,打印当前存储库的.git目录的完整路径。它将路径存储在$gitdir中。

if [ $(cat ${gitdir}/description) != "..." ]; then

这将执行cat ${gitdir}/description,打印当前存储库的.git/description的内容。如果您正确地命名了存储库,它将打印一个名称。否则,它将打印未命名的存储库;编辑这个文件'description'来命名存储库。

cat ${gitdir}/description

如果正确命名了repo,则打印内容。

else

否则……

echo "Unnamed repository!"

告诉用户回购是未命名的。


这个脚本中实现了类似的功能。

在git v2.7.0+中,为git-remote command引入了一个子命令get-url。

POSIX壳:

basename $(git remote get-url origin)

PowerShell:

Split-Path -Leaf (git remote get-url origin)

我认为这是明确识别存储库克隆的更好方法。

Git配置——获取remote.origin.url并检查以确保origin与ssh://your/repo匹配。