git Cookbook

Set local vars for username & email

First cd inside a repo, then:

git config user.name "John Doe"
git config user.email "name@example.com"

This leaves the global config in ~/.gitconfig untouched.


Create a new branch

git branch <branch-name>

# Then move to the new branch with:
git checkout <branch>

# or, in one step:
# "Specifying -b causes a new branch to be created as if git-branch[1] were called and then checked out. "
git checkout -b <branch>

Add a remote

git remote add {remote-name} {remote-url}

List all remotes

git remote -v

The optional -v flag tells git to also list the URLs of each remote.


Reset HEAD to a previous commit

git reset --hard {sha-of-commit}

Merge

First, switch to the destination branch -- that is, the branch that will receive the merge

git checkout {destination-branch}

Then issue a git merge with the branch to be merged as argument.

git merge --no-ff {source-branch}

The source branch will be merged into the destination branch. The optional --no-ff flag allows to write a commit message for the merge.


Edit an incorrect commit message

# w/ editor
git commit --amend #(opens default editor)

# w/ inline message
git commit --amend -m "{message}"

Update usernames & emails in existing commits

$ git filter-branch --env-filter '
WRONG_EMAIL="wrong@example.com"
NEW_NAME="New Name Value"
NEW_EMAIL="correct@example.com"

if [ "$GIT_COMMITTER_EMAIL" = "$WRONG_EMAIL" ]
then
    export GIT_COMMITTER_NAME="$NEW_NAME"
    export GIT_COMMITTER_EMAIL="$NEW_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$WRONG_EMAIL" ]
then
    export GIT_AUTHOR_NAME="$NEW_NAME"
    export GIT_AUTHOR_EMAIL="$NEW_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags

Remove an already tracked file or directory

To simulate the removal use the --dry-run, or -n, option:

git rm --cached --dry-run "{dir-name}"

For a file:

git rm --cached "{file-name}"

For a directory and its contents:

git rm --cached -r "{dir-name}"

To just simulate the removal:

git rm --cached --dry-run "{dir-name}"

The --cached option removes files only from the index, leaving their instances in the working tree untouched.