如何从GitHub URL提取仓库名?Bash与Git两种实现方案
从GitHub URL提取仓库名的两种方案
Bash脚本方案
针对给定的URL Https://github.com/RayaneQH/test.git,可以用以下几种Bash方法提取仓库名:
方法1:使用basename命令
basename可直接截取路径最后部分,再去除.git后缀:
url="Https://github.com/RayaneQH/test.git" repo_name=$(basename "$url" .git) echo "$repo_name" # 输出 test
方法2:使用sed正则匹配
通过正则表达式捕获仓库名部分:
url="Https://github.com/RayaneQH/test.git" repo_name=$(echo "$url" | sed -E 's/.*\/([^\/]+)\.git/\1/') echo "$repo_name" # 输出 test
方法3:使用awk分割字符串
以/分割URL,取最后一个字段并去掉.git后缀:
url="Https://github.com/RayaneQH/test.git" repo_name=$(echo "$url" | awk -F '/' '{gsub(/\.git$/, "", $NF); print $NF}') echo "$repo_name" # 输出 test
Git内置命令方案
如果涉及本地仓库或需要通过Git直接解析远程URL,可使用以下方法:
场景1:本地已克隆仓库
进入仓库目录后,直接获取与远程仓库名一致的本地目录名:
cd /path/to/cloned/repo repo_name=$(basename "$(git rev-parse --show-toplevel)") echo "$repo_name" # 输出 test
场景2:直接解析远程URL
无需克隆仓库,结合git ls-remote和basename处理:
url="Https://github.com/RayaneQH/test.git" repo_name=$(basename "$(git ls-remote --get-url "$url")" .git) echo "$repo_name" # 输出 test
若已添加远程仓库(如origin),可直接获取远程URL再处理:
repo_name=$(basename "$(git remote get-url origin)" .git) echo "$repo_name" # 输出 test
内容的提问来源于stack exchange,提问作者RayaneQH
相关产品推荐
相关产品推荐

