257

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
diveintohacking
  • 4,783
  • 6
  • 29
  • 43
  • 1
    It looks like this is what you're after. http://stackoverflow.com/questions/4076239/finding-out-the-name-of-the-original-repository-you-cloned-from-in-git – Max Sherman Mar 30 '13 at 06:54
  • No, that's probably not what he wants. This might be, though: http://stackoverflow.com/questions/957928/is-there-a-way-to-get-the-git-root-directory-in-one-command – Nevik Rehnel Mar 30 '13 at 07:03
  • if you use node.js you could try https://www.npmjs.com/package/git-repo-name – jonschlinkert Oct 20 '15 at 05: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 02 '21 at 23:28

20 Answers20

259

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.

Fuad Saud
  • 3,086
  • 1
  • 15
  • 16
  • 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 03 '14 at 01:32
  • 9
    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 '14 at 00: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? – Buttle Butkus Oct 29 '15 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 '16 at 09:29
  • More secure will be to use origin repo name cause basename can be changed on cloning when you will add "." -> "clone repo-name ." Bulletproof solution if you want to use repo name in script: http://stackoverflow.com/questions/8190392/is-there-a-git-command-that-returns-the-current-project-name – fearis Mar 17 '16 at 09:42
  • 2
    This isn't safe. Try cd /var/www/html `git --git-dir=/.git rev-parse --show-toplevel` and it'll give you back /var/www/html – sibaz Mar 02 '17 at 11:44
  • To make sure it works with long directories (with whitespaces), you would have to surround it with double quotes: ```basename "`git rev-parse --show-toplevel`"``` – fralau Feb 25 '19 at 19:19
  • This command only gives me the local name of the repository directory. ```basename -s .git `git config --get remote.origin.url````, mentioned below, worked as expected – Merovex Jun 24 '20 at 13:46
  • This command gives the name of the local directory containing the git repository, not the name the the git repository itself. By default `git clone` will use the same value for both of them but it might differ, so I think this is not so safe, event if it works in most of the cases. – Fabrice Jammes Aug 31 '20 at 08:53
  • Question was: _When you are working in some Git directory, how can you get the Git repository name?_ This answer gives the name of the Git directory, not the Git repository. – j1elo Jul 07 '22 at 12:41
  • Powershell : `Split-Path -Leaf (git rev-parse --show-toplevel)` – Dan Marshall Mar 28 '23 at 22:06
205

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.

mvp
  • 111,019
  • 13
  • 122
  • 148
  • 2
    You can always get branch name using well, `git branch` :) (active branch will be marked with star `*`). – mvp Jan 03 '14 at 04:10
176

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).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
TastyWheat
  • 2,127
  • 1
  • 13
  • 12
49

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)
Florian Castellane
  • 1,197
  • 2
  • 14
  • 38
vulcan raven
  • 32,612
  • 11
  • 57
  • 93
  • 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]` – Max Cascone May 08 '20 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()` – Max Cascone May 08 '20 at 20:33
  • 4
    This is pretty concise and clean! You can use `basename -s .git $(git remote get-url origin)` to remove the `.git` at the end. – Daniel Bang Sep 29 '21 at 16:19
27

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

animatedgif
  • 1,060
  • 12
  • 16
  • 6
    `git config --get remote.origin.url | sed -r 's/.*(\@|\/\/)(.*)(\:|\/)([^:\/]*)\/([^\/\.]*)\.git/https:\/\/\2\/\4\/\5/'` will convert BOTH `git@dom.tld: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 '20 at 23:56
20

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

dragn
  • 1,030
  • 1
  • 8
  • 21
  • 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 '15 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? – Arnout Engelen Nov 13 '15 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 '15 at 08:59
  • Makes sense! Good one! – Arnout Engelen Nov 16 '15 at 12:15
  • I went with this method but achieved it using `ack`. Avoids multiple `grep` and `sed` calls, and it works on on my osx with `zsh` where `sed -E` doesn't work as expected. Also puts the requirements in a single regex string instead of spread across a few. Uses named captures groups, `(?...)`, non-greedy matching, `.*?`, and optional matching, `(?:\.git|$)`. Here it is: `git remote show origin -n | ack -m1 --match "\bFetch URL:.*\/(?.*?)(?:\.git|$)" --output "$+{repo_name}"` – Trent Scheffert Dec 03 '15 at 19:03
  • 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 '16 at 22:37
  • There is no such thing as "real name". You may not even have remote called `origin`. Or, you can have multiple remotes, and each can call it differently. In git, repository name (or directory name it is contained) is not explicitly tracked. – mvp May 23 '16 at 17:17
  • `git --git-dir=/.git remote show origin -n | grep "Fetch URL:" | sed -E "s/^.*\/(.*)$/\1/" | sed "s/.git$//"` Worked for me. @MarkHu was closest – sibaz Mar 02 '17 at 11:47
  • With MacOS, use single quote: `git remote show origin -n | grep "Fetch URL:" | sed -E 's#^.*/(.*)$#\1#' | sed 's#.git$##'` – Scott Robert Schreckengaust Aug 29 '18 at 18:33
  • Can you explain me why you need to use single quotes for MacOX? In which conditions? And why not for the `grep`, then? Thanks. – user3341592 Dec 12 '19 at 08:19
  • Git is NOT Github or any other git hosting service. It's totally fine to create and use a git repo without any fetch URL. – oldherl Nov 26 '20 at 07:09
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
raw-bin hood
  • 5,839
  • 6
  • 31
  • 45
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.

OLIVER.KOO
  • 5,654
  • 3
  • 30
  • 62
  • 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 '18 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: https://stackoverflow.com/a/58843794/2696867 – animatedgif Nov 13 '19 at 18:56
4

Repo full name:

git config --get remote.origin.url | grep -Po "(?<=git@github\.com:)(.*?)(?=.git)"
Lemonada
  • 41
  • 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 '19 at 18:58
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'
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
nroose
  • 1,689
  • 2
  • 21
  • 28
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nevik Rehnel
  • 49,633
  • 6
  • 60
  • 50
  • 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 '13 at 16:46
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

whirlwin
  • 16,044
  • 17
  • 67
  • 98
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.

Patrick Simard
  • 2,294
  • 3
  • 24
  • 38
David
  • 35
  • 1
  • 1
    `git remote -v` is just returning one or more URLs. How is this answering the question? – Peter Mortensen Jul 17 '18 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 '19 at 19:03
  • i think this is right. the first word is the repository name which is commonly 'origin' – The OuterSpace Jun 26 '23 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.

MD XF
  • 7,860
  • 7
  • 40
  • 71
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)

Fabrice Jammes
  • 2,275
  • 1
  • 26
  • 39
1
git ls-remote --get-url | xargs basename -s .git # bar

# zsh
git ls-remote --get-url | read
print $REPLY:t:r # bar
Daniel Bayley
  • 1,493
  • 1
  • 10
  • 8
1

you might be after 'origin'

you can use git remote -v

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

The OuterSpace
  • 151
  • 1
  • 4
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
}
tamouse
  • 2,169
  • 1
  • 19
  • 26
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

Yevhenii Shashkov
  • 464
  • 1
  • 8
  • 19
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 user.email=you@example.com -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 user.email=you@example.com -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 user.email=you@example.com -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: ВашеИмя <you@example.com>
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

uanr81
  • 309
  • 2
  • 10