Git triks

| git

In this article I list some of git comands that I use time to time, but not enought to put them in my .gitconfig.

Rename branch

To change the name locally go into the branch you want to rename, and rename it

git switch <branch_name>
git branch -m <new_branch_name>

Or you can do it without changing branch

git branch -m <old_name> <new_name>

To change the name remotely you have to delete the old name and push the new branch

git push origin --delete <old_name>
git push origin -u <new_name>

Selective adding changes to staging area

git add -p <filename>

Git will break down your file into what it thinks are sensible “hunks” (portions of the file). It will then prompt you with this question: Stage this hunk [y,n,q,a,d,/,j,J,g,s,e,?]?

Here is a description of each option:

If the file is not in the repository yet, you can first do git add -N <filename>. Afterwards you can go on with git add -p <filename>.

You can use: git reset -p to unstage mistakenly added hunks

Stash single files

When you don’t want to stash all the edited files, but only a subset, you can use this command

git stash push <file1> <file2> .. <fileN>

To make the stash retrieval easier, add a message with -m <message>

Diff staged changes

git diff --staged

Remove files that have not been added to the staging area

git clean -df

Revert changes that have been pushed on remote

git diff master > branch.diff
git apply --reverse branch.diff
git rm branch.diff

Move last commit to another branch

git reset --mixed HEAD~1 # remove last commit and put your files outside the staging area
git stash
git switch <working_branch>
git stash apply
git commit

The use of stash make this method not prefered.

It might be a good chase to use cherry-pick to the <working_branch> of the wanted commit and then remove, undo, the commit to the unwanted branch.

Check if a folder changed

git diff --quiet HEAD <commit_to_compare> -- <dir_to_check> || echo changed

Note that git diff --quiet will exit 1 when there are changes.

For example if you want to check if your current branch has canges in the directory dir1 when compared to the previous commit:

git diff --quiet HEAD HEAD~1 -- dir1 || echo changed

You can do this even with the previous tag

git diff --quiet HEAD "$(git describe --tags --abbrev=0 HEAD)" -- dir1 || echo changed

I have used this command to help me automate my website release, How to deploy automatically a Hugo website.

Count commit messages that contains a string

git shortlog -sne --grep="a string" --grep="a second string"

To list only commits that contain all the strings given, all the --grep flags, you must add --all-match.

For example if you want to list all the commit messages that contains ‘WIP’ you have to write:

git shortlog -sne --grep="wip" --grep="WIP"