Git cookbook

Useful aliases

This is a list of useful aliases I’ve found on the Internet1. To use them, simply add them to the [alias] section of ~/.gitconfig.

Sync with main branch

This command updates the local branch with the origin’s main.

    synced = "!git pull origin $(git mainbranch) --rebase"


Truncate history

To truncate Git history, that is discard all commits before a specific one, you can do the following. Assume I have a commit with a certain hash, say abc123, and want to drop all commits before this one. Create a new orphan branch (name not important) called, say, truncated.

$ git checkout --orphan truncated abc123

And then rebase master (or any other main branch) on top of truncated.

$ git commit -m "Truncate history"
$ git rebase --onto truncated abc123 master

Your new branch truncated will be free of master history.



The pre-push script is called by git push, when the push actually happens. If the exit status is 0, then the push will proceed, otherwise it will be stopped.

The script is supplied with the following arguments:

 $1 -- Name of the remote to which the push is being done (Ex: origin)
 $2 -- URL to which the push is being done (Ex: https://<host>:<port>/<username>/<project_name>.git)

Information about the commits which are being pushed is supplied as lines to the standard input in the form:

<local_ref> <local_sha1> <remote_ref> <remote_sha1>

Sample values:

local_ref = refs/heads/master
local_sha1 = 68a07ee4f6af8271dc40caae6cc23f283122ed11
remote_ref = refs/heads/master
remote_sha1 = efd4d512f34b11e3cf5c12433bbedd4b1532716f