从 bash 中的 GitHub url 中提取存储库名称

Jus*_*tin 12 bash regex strings regular-expressions github

给定任何 GitHub 存储库 url 字符串,例如:

git://github.com/some-user/my-repo.git
Run Code Online (Sandbox Code Playgroud)

或者

git@github.com:some-user/my-repo.git
Run Code Online (Sandbox Code Playgroud)

或者

https://github.com/some-user/my-repo.git
Run Code Online (Sandbox Code Playgroud)

从以下任何字符串中bash提取存储库名称的最佳方法是什么my-repo?该解决方案必须适用于上面指定的所有类型的 url。

谢谢。

qua*_*nta 19

$ url=git://github.com/some-user/my-repo.git
$ basename=$(basename $url)
$ echo $basename
my-repo.git
$ filename=${basename%.*}
$ echo $filename
my-repo
$ extension=${basename##*.}
$ echo $extension
git
Run Code Online (Sandbox Code Playgroud)

  • `echo $(basename "$url" ".${url##*.}")`。 (2认同)

wom*_*ble 15

我会去的basename $URL .git

  • 最佳答案。还有最短的 (2认同)

小智 10

旧帖子,但我最近遇到了同样的问题。

正则表达式^(https|git)(:\/\/|@)([^\/:]+)[\/:]([^\/:]+)\/(.+).git$适用于三种类型的 URL。

#!/bin/bash

# url="git://github.com/some-user/my-repo.git"
# url="https://github.com/some-user/my-repo.git"
url="git@github.com:some-user/my-repo.git"

re="^(https|git)(:\/\/|@)([^\/:]+)[\/:]([^\/:]+)\/(.+).git$"

if [[ $url =~ $re ]]; then    
    protocol=${BASH_REMATCH[1]}
    separator=${BASH_REMATCH[2]}
    hostname=${BASH_REMATCH[3]}
    user=${BASH_REMATCH[4]}
    repo=${BASH_REMATCH[5]}
fi
Run Code Online (Sandbox Code Playgroud)

解释(参见 regex101 上的操作):

  • ^ 匹配字符串的开头
  • (https|git)匹配并捕获字符httpsgit
  • (:\/\/|@)匹配并捕获字符://@
  • ([^\/:]+)匹配并捕获一个或多个/非或非字符:
  • [\/:]匹配一个字符 /:
  • ([^\/:]+)再次匹配并捕获一个或多个不是/或者 的字符:
  • [\/:] 匹配字符 /
  • (.+) 匹配并捕获一个或多个字符
  • .git匹配... .git,字面意思
  • $ 匹配字符串的结尾

这远非完美,就像https@github.com:some-user/my-repo.git匹配的东西一样,但我认为它足以提取。

  • 有些网址末尾没有“.git”。 (2认同)
  • 我正在使用扩展版本(在 [regex101](https://regex101.com/r/liVozi/1) 上使用它: `^((https?|ssh|git|ftps?):\/\/ )?(([^\/@]+)@)?([^\/:]+)[\/:]([^\/:]+)\/(.+).git\/?$ `,它更符合 [URL 的官方规范](https://git-scm.com/docs/git-push#URLS)。第 2 组是方案,如果缺少默认值是 `ssh`。 (2认同)

小智 6

加起来: