270

When you are working in some Git directory, how can you get the Git repository name in some Git repository? Are there any Git commands?

# 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
4
  • 1
    It looks like this is what you're after. stackoverflow.com/questions/4076239/… Mar 30, 2013 at 6:54
  • No, that's probably not what he wants. This might be, though: stackoverflow.com/questions/957928/… Mar 30, 2013 at 7:03
  • if you use node.js you could try npmjs.com/package/git-repo-name Oct 20, 2015 at 5:21
  • There Is No Good Answer because there is no answer. Some answers get get you the directory name where you could have elected an alternate name to clone into (or just rename). Other's have you look at the remote - but multiple remotes is a thing origin just happens to be a default. And one answer suggests look in .git/description - sorry if not used consistently by all git hosts this is useless too
    – nhed
    Apr 2, 2021 at 23:28

21 Answers 21

269

In Git, there's no concept of a repository name. The repository itself is kept under a directory in the file system (the one that contains the .git directory) and you can get the name of that directory with the following command:

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

The git rev-parse --show-toplevel part gives you the path to that directory and basename strips the first part of the path.


Another common sense interpretation to a "Git's repository name" is the name used to identify the repository in a Git hosting service (such as GitHub or GitLab). That name can be obtained by looking at the remote information, and a few different ways to achieve that are documented in other answers to this question.

12
  • 17
    As @mvp says below, you can change the name of the directory containing the .git subdirectory, so it's not true that "if, for the repository name you mean the git root directory name".
    – sheac
    Sep 3, 2014 at 1:32
  • 10
    This command gives you exactly that: the name of the directory directly above the .git dir. That is one interpretation for "the name of the repository", and it seems it's the one OP was looking for. Obviously there are other valid interpretations, like the name of the remote origin repository. There's no universal truth in this case and it really depends on what you want.
    – Fuad Saud
    Oct 24, 2014 at 0:08
  • 1
    Doesn't work in windows 8.1 when my directory looks like "Project 1.1". It only echoes "Project". Plus the folder name here isn't necessarily related to my repo name, right? Oct 29, 2015 at 23:59
  • Additional question: how add this to be a string in chain line like : git remote add test "admin@sed -n '1 p' test.ip | basename basename git rev-parse --show-toplevel `:/var/www" ?? As You probably see this line will not work cause of using `` inside ``
    – fearis
    Mar 17, 2016 at 9:29
  • 3
    This isn't safe. Try cd /var/www/html git --git-dir=<some git repo>/.git rev-parse --show-toplevel and it'll give you back /var/www/html
    – sibaz
    Mar 2, 2017 at 11:44
211

In general, you cannot do this. Git does not care how your git repository is named. For example, you can rename directory containing your repository (one with .git subdirectory), and git will not even notice it - everything will continue to work.

However, if you cloned it, you can use command:

git remote show origin

to display a lot of information about original remote that you cloned your repository from, and it will contain original clone URL.

If, however, you removed link to original remote using git remote rm origin, or if you created that repository using git init, such information is simply impossible to obtain - it does not exist anywhere.

1
  • 3
    You can always get branch name using well, git branch :) (active branch will be marked with star *).
    – mvp
    Jan 3, 2014 at 4:10
180

There's no need to contact the repository to get the name, and the folder name won't necessarily reflect the remote name.

I've found this to be the most accurate and efficient way to get the current repository name:

basename -s .git `git config --get remote.origin.url`

This should work as of Git 1.8.1.5. Prior to this, the now deprecated git-repo-config command would have worked (as early as Git 1.7.5).

6
  • 5
    Agreed, this is the most clean answer (I used to have ${PWD##*/} but as you say, the current folder name may be different from the origin) Mar 28, 2017 at 6:13
  • yes, i was looking for this, much appreciated.! my folder name differed ;)
    – csomakk
    Feb 11, 2020 at 15:58
  • This one also works: basename -s .git $(git --git-dir=/<project-path>/.git remote get-url origin) Apr 20, 2020 at 8:24
  • In addition, commad above: basename -s .git $(git --git-dir=/<project-path>/.git remote get-url origin) can be launched from anywhere, you do not need to be inside the git repository. Aug 31, 2020 at 8:58
  • bash git config --get remote.origin.url Works
    – Anis
    Apr 6, 2022 at 5:29
52

In git v2.7.0+, a subcommand get-url was introduced to git-remote command.

POSIX shell:

basename $(git remote get-url origin)

PowerShell:

Split-Path -Leaf (git remote get-url origin)
3
  • 2
    I get the .git at the end of my string using this method, so I added a split to strip it off: (git remote get-url origin | Split-Path -leaf).split('.')[0] May 8, 2020 at 20:14
  • If you happen to be using this in Jenkins, you'll want to strip off the trailing newline with a trim() : def repo = powershell(returnStdout: true, script: "(git remote get-url origin | Split-Path -leaf).split('.')[0]" ).trim() May 8, 2020 at 20:33
  • 5
    This is pretty concise and clean! You can use basename -s .git $(git remote get-url origin) to remove the .git at the end. Sep 29, 2021 at 16:19
31

If you are trying to get the username or organization name AND the project or repo name on github, I was able to write this command which works for me locally at least.

▶ git config --get remote.origin.url
# => https://github.com/Vydia/gourami.git

▶ git config --get remote.origin.url | sed 's/.*\/\([^ ]*\/[^.]*\).*/\1/' # Capture last 2 path segments before the dot in .git
# => Vydia/gourami

This is the desired result as Vydia is the organization name and gourami is the package name. Combined they can help form the complete User/Repo path

1
  • 6
    git config --get remote.origin.url | sed -r 's/.*(\@|\/\/)(.*)(\:|\/)([^:\/]*)\/([^\/\.]*)\.git/https:\/\/\2\/\4\/\5/' will convert BOTH [email protected]:User/Repo.git AND https://dom.tld/User/Repo.git to https://dom.tld/User/Repo. Got there thanks to your sed idea
    – Reed
    Aug 22, 2020 at 23:56
21

Other answers still won't work when the name of your directory does not correspond to remote repository name (and it could). You can get the real name of the repository with something like this:

git remote show origin -n | grep "Fetch URL:" | sed -E "s#^.*/(.*)$#\1#" | sed "s#.git$##"

Basically, you call git remote show origin, take the repository URL from "Fetch URL:" field, and regex it to get the portion with name: https://github.com/dragn/neat-vimrc.git

11
  • 1
    Yeah, this is okay, but this will query the remote for an update. It is better to use git remote show origin -n to prevent that.
    – Ryanmt
    May 14, 2015 at 21:15
  • 1
    Can we update the sed command to also work when the origin url does not end in .git? so 'foo.git' becomes 'foo', but 'foo' is also matched? I guess we need non-greedy matching? Nov 13, 2015 at 16:38
  • @ArnoutEngelen I think that the simplest thing to do is to (optionally) strip .git with another call to sed, I've updated the code in the answer. This way it will work, when the URL does not end with .git.
    – dragn
    Nov 16, 2015 at 8:59
  • Makes sense! Good one! Nov 16, 2015 at 12:15
  • 9
    This simpler sed worked better on my Mac OSX: git remote show origin -n | grep h.URL | sed 's/.*://;s/.git$//'
    – MarkHu
    Mar 22, 2016 at 22:37
8

A little bit late for this question, but if you:

cat /path/to/repo/.git/config

You will see the url of the repository which will include the reponame:

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    ignorecase = true
    precomposeunicode = true
[remote "origin"]
    url = https://github.com/your_git_user_name/your_git_repo_name.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
6

I think this is a better way to unambiguously identify a clone of a repository.

git config --get remote.origin.url and checking to make sure that the origin matches ssh://your/repo.

2
  • 1
    Actually a stronger condition, requires less parsing. Might have to specify url name instead of project name, but a small price to pay. The way everyone else is doing it would break if ".git" occurred in the repo name. Unlikely, but possible.
    – gamesguru
    Sep 14, 2018 at 11:01
  • 1
    @ShaneJ you're right and you prompted me to write my own answer which handles the ".git" in the remote origin repo name: stackoverflow.com/a/58843794/2696867 Nov 13, 2019 at 18:56
4

Repo full name:

git config --get remote.origin.url | grep -Po "(?<=git@github\.com:)(.*?)(?=.git)"
1
  • In the question, gipcompany mentions being somewhere deep down the directory hierarchy. While I'm not sure what he actually wants (there's an example - might be "get the Git repository name from anywhere in that Git repository" (which is at odds with how I imagine git repositories)), I see no indication that a/the URL should be known.
    – greybeard
    Jul 14, 2019 at 18:58
3

you might be after 'origin'

you can use git remote -v

the first word is the repository name which is commonly named as 'origin'

2

If you want the whole GitHub repository name ('full name') - user/repository, and you want to do it in with Ruby...

git remote show origin -n | ruby -ne 'puts /^\s*Fetch.*:(.*).git/.match($_)[1] rescue nil'
0
1

This approach using git-remote worked well for me for HTTPS remotes:

$ git remote -v | grep "(fetch)" | sed 's/.*\/\([^ ]*\)\/.*/\1/'
                                                |  |        | |
                                                |  |        | +---------------+
                                                |  |        | Extract capture |
                                                |  +--------------------+-----+
                                                |Repository name capture|
                                                +-----------------------+

Example

1

You can use: git remote -v

Documentation: https://git-scm.com/docs/git-remote

Manage the set of repositories ("remotes") whose branches you track. -v --verbose Be a little more verbose and show remote url after name. NOTE: This must be placed between remote and subcommand.

3
  • 1
    git remote -v is just returning one or more URLs. How is this answering the question? Jul 17, 2018 at 12:39
  • As stated earlier, this returns only URLs... and it returns 2 URLs separated by a line break, with unnecessary chars before the URL. SO it creates a problem by including unneeded info, then presents two paths to search, then it still doesn't get the name of the repo.
    – Andrew
    Mar 12, 2019 at 19:03
  • i think this is right. the first word is the repository name which is commonly 'origin' Jun 26, 2023 at 18:01
1

Here's a bash function that will print the repository name (if it has been properly set up):

__get_reponame ()
{
    local gitdir=$(git rev-parse --git-dir)

    if [ $(cat ${gitdir}/description) != "Unnamed repository; edit this file 'description' to name the repository." ]; then
        cat ${gitdir}/description
    else
        echo "Unnamed repository!"
    fi
}

Explanation:

local gitdir=$(git rev-parse --git-dir)

This executes git rev-parse --git-dir, which prints the full path to the .git directory of the currrent repository. It stores the path in $gitdir.

if [ $(cat ${gitdir}/description) != "..." ]; then

This executes cat ${gitdir}/description, which prints the contents of the .git/description of your current repository. If you've properly named your repository, it will print a name. Otherwise, it will print Unnamed repository; edit this file 'description' to name the repository.

cat ${gitdir}/description

If the repo was properly named, then print the contents.

else

Otherwise...

echo "Unnamed repository!"

Tell the user that the repo was unnamed.


Something similar is implemented in this script.

1

Unfortunately, it seems that Git has no such command built in. But you can easily add it yourself with Git aliases and some shell magic.

As pointed out by this answer, you can use git rev-parse --show-toplevel to show the root of your current Git folder.

If you want to use this regularly, it's probably more convenient to define it as an alias. For this, used git config alias.root '!echo "$(git rev-parse --show-toplevel)"'. After this, you can use git root to see the root folder of the repository you're currently in.

If you want to use another subcommand name than root, simply replace the second part of alias.root in the above command with whatever you want.

For details on aliases in Git, see also the git config man page.

1
  • 2
    git config --add alias.root 'rev-parse --show-toplevel' -- there's no need to throw in the shell for a single-command alias.
    – kostix
    Mar 31, 2013 at 16:46
1

This one works pretty well with git-2.18.2 and can be launched from outside git target repository:

basename -s .git $(git --git-dir=/<project-path>/.git remote get-url origin)

1
git ls-remote --get-url | xargs basename -s .git # bar

# zsh
git ls-remote --get-url | read
print $REPLY:t:r # bar
1

If the repo name may have more than 1 folder level then "basename" isn't enough.

I find the following the simplest to cover all cases:

git remote get-url origin | sed 's/^.*://;s/.git$//'

This command will produce a single line with the repo url wich can easilly be filtered with sed to extract just the name from it.

0

Here's mine:

git remote --verbose | grep origin | grep fetch | cut -f2 | cut -d' ' -f1

no better than the others, but I made it a bash function so I can drop in the remote name if it isn't 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
}
0

Also I just find that there is some repo information inside .git directory. So you can just watch FETCH_HEAD file in terminal to see repo's name:

Example:

cd your_project_folder/.git
more FETCH_HEAD

Output:

672e38391557a192ab23a632d160ef37449c56ac        https://bitbucket.org/fonjeekay/some_repo

And https://bitbucket.org/somebituser/some_repo.git is the name of your repository

0

You can store the project name in an object in the git object database and reference it in the annotated tag.

For example, the repository name "GnuMake" is the tag name "nameRepo". ssh -F specifies the ssh configuration file khnSrv_al is registered as a remote host

Command: Create and place an object in a git database, get and save a link to the placed object in the annotated tag.

git -C /path/dir_git -c [email protected] -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 [email protected] -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 [email protected] -c user.name=ВашеИмя tag -a nameRepo -m 'Имя репозитория' \$(echo 'GnuMake'|git -C /home/al/newRepos/GNU_Make hash-object -w --stdin)"

Command: Extract the repository name from a git database object using a tag named "nameRepo"

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: ВашеИмя <[email protected]>
Date:   Wed Jan 25 09:01:18 2023 +0200

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

Note that it is not necessary to have anything else in the repository other than this and you can create a repository name at any time

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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