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

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

当目录名称与远程存储库名称不对应时,其他答案仍然不起作用(它可以)。 你可以通过这样的方式获取存储库的真实名称:

git远程显示起源- n | grep获取URL: | sed - e” #^.*/(.*)$#\ 1 #“| sed”# . # #美元”

基本上,你调用git remote show origin,从“Fetch URL:”字段中获取存储库URL,并正则化它以获得带有名称的部分: https://github.com/dragn/neat-vimrc.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是包名称。它们组合在一起可以帮助形成完整的用户/回购路径

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

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

这是我的:

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
}