Git Tips And Tricks

Various Git tips I learnt along the way

Write the commit message inline

1
git commit -m "message ..."

Skip pre-commit hook

1
git commit -n

Skip pre-push hook

1
git commit --no-verify

Show local and remote branches

1
2
git branch
git branch -r

See branches sorted by the last commit

1
git branch --sort=-committerdate

Note: some git commands require installing globally NPM module diff-so-fancy.

1
npm i -g diff-so-fancy

Merge another branch with default message

1
2
3
# we are in the current branch X
# and want to merge the branch "main"
git merge main --no-edit

See the diffs with the log

1
git log -p

Get the file from another branch

1
2
3
git checkout <branch name> <filename>
# even from another commit
git checkout <sha> <filename>

Checkout previous branch

Just like cd - goes to the previous working directory, git checkout - goes to the previously checkout branch.

Git CLI commands

I use git-extras to perform all my Git commands from the terminal.

Discard local changes

If you worked on files and then want to get back to the commit and discard (throw away) your changes

1
$ git reset --hard

Remove untracked files

Sometimes you get a bunch of generated files in the repo, and would like to remove them.

1
2
3
4
5
6
# first, see which files will be removed
$ git clean -d -n
# you can go through each file and confirm you want it deleted
$ git clean -d -i
# or if you are sure, delete them
$ git clean -d -f

Merge another branch with default merge message

Typically, if you execute git merge <branch name> it merges that branch into the current branch. The merge creates a commit and Git asks you to edit the commit message. You can avoid editing and just accept the default message.

1
$ git merge <branch name> --no-edit

Copying a repository

To quickly download a snapshot of a remote repository and remove its .git folder (for example to start your own project), use the tool degit. You can even specify a tag to clone and subfolder

1
2
3
$ npx degit user/repo
$ npx degit user/repo#tag
$ npx degit user/repo/path/to/subfolder

See more

Read my other Git blog posts, starting with Git aliases.

Related posts