8

Given ANY GitHub repository url string like:

git://github.com/some-user/my-repo.git

or

git@github.com:some-user/my-repo.git

or

https://github.com/some-user/my-repo.git

What is the best way in bash to extract the repository name my-repo from any of the following strings? The solution MUST work for all types of urls specified above.

Thanks.

16
$ 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
  • Thanks, trying to make it a one liner, but not working. REPO_NAME=${`basename $REPO_URL`%.*} – Justin Aug 14 '12 at 4:17
  • 1
    echo $(basename "$url" ".${url##*.}"). – quanta Aug 14 '12 at 6:31
  • +1. Is there anything similar to get the hostname, i.e. github.com, instead, @quanta? – chepukha Mar 31 '15 at 2:19
10

I'd go with basename $URL .git.

7

Old post, but I faced the same problem recently.

The regex ^(https|git)(:\/\/|@)([^\/:]+)[\/:]([^\/:]+)\/(.+).git$ works for the three types of 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

Explaination (see it in action on regex101):

  • ^ matches the start of a string
  • (https|git) matches and captures the characters https or git
  • (:\/\/|@) matches and captures the characters :// or @
  • ([^\/:]+) matches and captures one character or more that is not / nor :
  • [\/:] matches one character that is / or :
  • ([^\/:]+) matches and captures one character or more that is not / nor :, yet again
  • [\/:] matches the character /
  • (.+) matches and captures one character or more
  • .git matches....git, literally
  • $ matches the end of a string

This if far from perfect, as something like https@github.com:some-user/my-repo.git would match, but I think it's fine enough for extraction.

  • 🏆this is gold! – Omri Jul 1 '18 at 14:24
  • some urls don't have .git at the end. – kenn Jan 2 at 14:58
5

Summing up:

  • Get url without (optional) suffix:

    url_without_suffix="${url%.*}"
    
  • Get repository name:

    reponame="$(basename "${url_without_suffix}")"
    
  • Get user (host) name afterwards:

    hostname="$(basename "${url_without_suffix%/${reponame}}")"
    
0

use regular expression: /([^/]+)\.git$/

0
basename $git_repo_url | tr -d ".git"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.