Git triks

| git

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.

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>

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

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 changes 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 .