当您在某个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-2.18.2中运行得非常好,并且可以从git目标库外部启动:

Basename -s .git $(git——git-dir=/<项目路径>/.)Git远程获取url来源)

其他回答

另外,我刚刚发现在.git目录中有一些回购信息。所以你可以在终端中查看FETCH_HEAD文件来查看repo的名称:

例子:

cd your_project_folder/.git
more FETCH_HEAD

输出:

672e38391557a192ab23a632d160ef37449c56ac        https://bitbucket.org/fonjeekay/some_repo

https://bitbucket.org/somebituser/some_repo.git是存储库的名称

如果你试图获得用户名或组织名称和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是包名称。它们组合在一起可以帮助形成完整的用户/回购路径

下面是一个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 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
}

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

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

例子