Useful git snippets

April 05, 2013

Not so much a blog post as a notebook for useful git commands…

Export changes from a range of revisions

git archive --output=../my_archive.tar HEAD $(git diff-tree -r --no-commit-id --name-only --diff-filter=ACRMT revision_id_1..revision_id_2)

Keep your fork in sync with the main repo

Alias for deleting all branches whose commits have already been merged into the develop branch

# if the main branch is develop:
alias gitpruned='git fetch;git checkout develop;git pull upstream develop; git branch --merged develop | grep -v "\* develop" | xargs -n 1 git branch -d'

# if the main branch is master:
alias gitprunem='git fetch;git checkout master;git pull upstream master;git branch --merged master | grep -v "\* master" | xargs -n 1 git branch -d'

From a StackOverflow answer Need to be careful with this if you have a local checkout of master or release branches, and merges from them. git-fresh is similar, but more useful

Split a repo

git filter-branch --subdirectory-filter DIRECTORY_YOU_WANT_TO_KEEP/ -- master

From the Atlassian blog

Maintain mirrors of a remote

For example, this is useful if you are managing a module on, but maintaining the code using GitHub pull requests. If you do this, make sure that you have the email address used on GitHub added as a secondary email address on, and vice versa. It’s also a good idea to follow Drupal’s commit message standards

git clone -o github [email protected]:Capgemini/spalp.git
cd spalp
git remote add drupal [email protected]:project/spalp.git

# usually not necessary
git pull --rebase github 8.x-1.x

Get a file from another branch

git checkout otherbranch -- filename.ext

Compare commits between branches

git log --oneline master..otherbranch