Skip to main content
ubuntuask.com

Back to all posts

Git Refspec

Published on
2 min read

Table of Contents

Show more
Git Refspec image

Git refspecs specifies the patterns for references on the remote side and the locally tracked branch. When you create a new repository and add a new remote to it i.e git remote add origin url

This command will modify your .git/config file and add a remote name, the URL of the remote repository and the refspec to be used for fetching.

For example

[remote "origin"]         url = https://github.com/ fetch =+refs/heads/*: refs/remotes/origin/*

The pattern is a src:dst pattern. The plus tells git to update the references even if it isn’t fast-forward. The src is the references on the remote where dst is the references that are being tracked locally. This refspec will fetch all the references on the server and writes them under ../remotes/origin locally.

In essence, the following 3 commands are equal:

git log orogin/master

git log remotes/origin/master

git log refs/remotes/origin/master

Update the refspec to only the remote branch that you want git to pull down every time if you to not want all the branches under ref to be pullled down. i.e

fetch = + refs/heads/master:refs/remotes/origin/localmaster

You likewise can fetch multiple refspces i.e

git fetch origin master:refs/remotes/origin/localmaster \ staging: refs/remotes/origin/staging

If a branch is not listed as a fast forward reference, once can override it by adding a + infront of the refspec.

Also in the configuration file, multiple refspecs can be specified for different specific branches. You can as well specify namespaces (or directories) as part of the refspec. For example, if there is a specific project, which has own namespace, you can specify the refspec as :

fetch = +refs/heads/otherproject/*:refs/remotes/origin/otherproject/*

This will fetch only branches from the “otherproject” namespace.

Similarly to fetch, you can specify a refspec for push. In the config file, add a psuh configuration i.e

push = refs/heads/branch_name:refs/heads/otherproject/branch_name

or simply on the command line by always running

git push origin master: refs/heads/master

To delete references from the remote server, you can also use refspec.

git push origin   :branch_name

By leaving the src part of the respec blank, this means push nothing to the remote, which essentially deletes the remote branch. Be a little careful with this tho.

You can similarly delete a remote branch by running

git push origin --delete branch_name