如何在fetch并checkout后获取Git仓库的humanish目录名?
获取Git仓库的humanish名称
一、已初始化本地仓库(执行过git init+fetch+checkout)的场景
如果你已经在本地目录完成了git init、git fetch <远程URL>和git checkout FETCH_HEAD操作,想要获取该远程仓库对应的humanish名称,可以按以下步骤操作:
提取远程仓库的URL
从本地Git的FETCH_HEAD文件中获取之前fetch的远程URL,执行命令:fetch_url=$(awk '{print $2}' .git/FETCH_HEAD)从URL中提取humanish名称
用以下命令处理URL,得到符合git clone规则的humanish名称:humanish=$(echo "$fetch_url" | sed -e 's/\.git$//' -e 's/.*[\/:]//' -e 's/\/$//') echo "$humanish"这个命令会依次完成:去掉URL末尾的
.git后缀、截取最后一个斜杠/或冒号:之后的内容、去掉末尾可能存在的斜杠,最终得到humanish名称。
二、直接从仓库URL提取humanish名称(无需克隆/初始化)
如果只是拿到一个仓库URL,想直接得到git clone默认会使用的目录名(即humanish名称),可以直接用上述的提取命令处理URL:
比如处理host.xz:foo/.git:
url="host.xz:foo/.git" humanish=$(echo "$url" | sed -e 's/\.git$//' -e 's/.*[\/:]//' -e 's/\/$//') echo "$humanish"
输出结果为foo。
再比如处理https://github.com/root-project/cling:
url="https://github.com/root-project/cling" humanish=$(echo "$url" | sed -e 's/\.git$//' -e 's/.*[\/:]//' -e 's/\/$//') echo "$humanish"
输出结果为cling。
内容的提问来源于stack exchange,提问作者nfl
相关产品推荐
相关产品推荐

