当您在某个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根目录名(包含.git目录的根目录名),你可以这样运行:

basename `git rev-parse --show-toplevel`

git rev-parse——show-toplevel部分提供了该目录的路径,basename删除了路径的第一部分。

其他回答

这是我的:

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

基本上,你调用git remote show origin,从“Fetch URL:”字段中获取存储库URL,并正则化它以获得带有名称的部分: https://github.com/dragn/neat-vimrc.git

在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对象数据库中的对象中,并在带注释的标记中引用它。

例如,存储库名称“GnuMake”就是标记名称“nameRepo”。ssh -F指定ssh配置文件khnSrv_al注册为远端主机

命令:在git数据库中创建并放置一个对象,在带注释的标记中获取并保存到放置对象的链接。

git -C /path/dir_git -c user.email=you@example.com -c user.name=ВашеИмя tag -a nameRepo -m 'Имя репозитория' $(echo 'GnuMake'|git -C /path/dir_git hash-object -w --stdin)

al@rznCad:~$ git -C ~/experiments/git -c user.email=you@example.com -c user.name=ВашеИмя tag -a nameRepo -m 'Имя репозитория' $(echo 'GnuMake'|git -C ~/experiments/git hash-object -w --stdin)

al@rznCad:~$ ssh -F /ubData/docs/PktDstSSH/master_config khnSrv_al "git -C /home/al/newRepos/GNU_Make -c user.email=you@example.com -c user.name=ВашеИмя tag -a nameRepo -m 'Имя репозитория' \$(echo 'GnuMake'|git -C /home/al/newRepos/GNU_Make hash-object -w --stdin)"

命令:使用名为"nameRepo"的标记从git数据库对象中提取存储库名称

git -C /path/dir_git cat-file blob nameRepo

al@rznCad:~$ git -C ~/experiments/git cat-file blob nameRepo
=>GnuMake

al@rznCad:~$ ssh -F /ubData/docs/PktDstSSH/master_config khnSrv_al "git -C /home/al/newRepos/GNU_Make cat-file blob nameRepo"
=>GnuMake

al@rznCad:~$ ssh -F /ubData/docs/PktDstSSH/master_config khnSrv_al git -C /home/al/newRepos/GNU_Make show nameRepo
tag nameRepo
Tagger: ВашеИмя <you@example.com>
Date:   Wed Jan 25 09:01:18 2023 +0200

Имя репозитория
GnuMake

注意,在存储库中不需要有其他任何东西,您可以在任何时候创建一个存储库名称

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

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