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