当您在某个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 config --get remote.origin.url | grep -Po "(?<=git@github\.com:)(.*?)(?=.git)"

其他回答

下面是一个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的方法对我来说很有效,适用于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-2.18.2中运行得非常好,并且可以从git目标库外部启动:

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

这是我的:

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
}