Useful Tips, Tricks, and Hacks to Mastering Git

Like another developers, I’m using Git to managing my codes and use GitHub, BitBucket to storing my projects. Git is very easy to learn because you only need a basic command of Git to make the source code management utility incredibly useful but it’s not easy to master. In the process of your projects you might have some problem with Git like: Untracked Binaries, Redo reset command, redo last commit …
Here is a list of a few Git hints, tips and tricks, starting from beginner and progressing to more advanced levels that can help you solve your problem.

Helpful Hints, Tips, Tricks to Mastering Git, GitHub

The following tips and tricks is a series of GIT commands that will take you deep into Git to give you the working knowledge you need to confidently use this system.

Common Git Problems & How to solve them

GitHub, BitBucket Always asked for password, even after uploading my public SSH key

This is very common problem, it’s happened when you clone a repository, pull or push a commit but don’t know why and how to fix it. As you may know, when you set up SSH, you create a key pair that contains a private key (saved to your local computer) and a public key (uploaded to BitBucket, GitHub). They use the key pair to authenticate anything the associated account can access.
In most common cases, the URL for origin/master is not ssh protocol, it’s url = http(s)://username@host/path/to/repo for the example. If it is using http it will ask for password irrespective of your ssh keys.
In your cloned repository you have a .git folder with a config file inside. Open it and confirm that it’s ssh protocol.
You should see something like :

[remote "origin"]
    url = ssh://[email protected]:/.git

Commit your changes or stash them before you can merge

Some changes have been made to the code in the repository. We’re now getting the error when push the commits to repository:

error: Your local changes to the following files would be overwritten by merge:
blah, blah, blah ...
Please, commit your changes or stash them before you can merge.
Aborting

I’ve read quite a few threads online, and several different options have been suggested.

Method 1

One approach was run:

git stash
 git pull
 git stash pop

Method 2

I had to do:

git reset --hard FETCH_HEAD

Method 3

git fetch origin
git reset --hard origin/master

Hope you can find the working solution.

Auto-Completion Git commands

Git comes with a nice auto-completion script that you can enable if you use Bash shell (Linux, MacOS). To turn-on this feature, you need download it from the Git source to get fresh version:

$ wget https://github.com/git/git/blob/master/contrib/completion/git-completion.bash

It’s located at /usr/share/git/completion but the director path maybe difference vary according to the distribution. (If you use zhs or tcsh you can change the suffix of git-completion.bash to download the correct file.)
Now, include it in .bashrc then tell Bash shell source it:

if [ -f ~/git-completion.bash ]; then
    source ~/git-completion.bash
fi

Press the Tab key twice when you’re writing a Git command, and it should return a set of suggestions for you to pick, let’s see:

$ git co<tab><tab>
column commits   config   
$ git co

That’s a pretty nice trick and may save you some time and documentation reading.

Display current git repository status

Similar auto-completion git command, you can display the repository status in Bash shell if the current position is git repository.
Add this code into .bashrc:

if [ -f ~/.git-prompt.sh ]; then
  source ~/.git-prompt.sh
fi

~/.git-prompt.sh can get from https://github.com/git/git/tree/master/contrib/completion or /usr/share/git/completion.
Now add \$(__git_ps1) to your prompt declaration. You can put it wherever you like, but I think it’s best suited for the very end, right before the final dollar sign (\$) If you want to get all fancy, you can make it a pretty color.
Here is mine:

Git Auto-Completion and Git Status in Bash Shell
Git Auto-Completion and Git Status in Bash Shell

Git clone repository to specified folder

When you want to clone a Git repository, you move to specified folder then type git clone command. Now you can clone it to specified folder from everywhere:

$ git clone @:.  
$ git clone https://github.com/Narga/narga-core /path/to/specified/folder/narga-core

Empty commits

Git won’t allow you to create empty commits unless you force it with --allow-empty argument to the git commit command.

$ git commit --allow-empty

Revert to previous Git commit

Before rewrite your commit histories, I recommend you get the reference information about your commits with git reflog command. The reflog is useful in various Git commands, to specify the old value of a reference.

Git reflog is to manage the information recorded in git
Git reflog is to manage the information recorded in git

The latest commit is 3d5fd13 or HEAD@{0}. If you want to try that commit again, you can run commit with the --amend option.

$ git add forgotten_file
$ git commit --amend

With git commands above, you can add more files which you’ve changed but forgot to include it in your commit.
If you want to temporarily go back to it, fool around, then come back to where you are, all you have to do is check out the desired commit:

# This will detach your HEAD, i.e. leave you with no branch checked out.
# Clear working directory tree from all changes
$ git checkout -f HEAD
# or
$ git checkout 3d5fd13

To revert to previous commit, ignoring any changes

If you haven’t published any of these commits, simply reset:

# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 3d5fd13

# Alternatively, if there's work to keep:
git stash
git reset --hard 3d5fd13
git stash pop
# This saves the modifications, then applies that patch after resetting.
# You could get merge conflicts, if you've modified things which were
# changed since the commit you reset to

# It also takes ranges. This will revert the last two commits:
git revert HEAD~2..HEAD

With git reset --hard HEAD~# command, you can jump into any commit that you’ve submitted, it’s very helpful to undo, redo, revert your codes. Yes, I love it too much. :)
I found the helpful git command called as git back in git-extras package, it’s required to using:

# remove the latest 3 commits
git back 3

Amend previous commit only

You can use git reset --soft to change the version you want to have as parent for the changes you have in your index and working tree. For example: I made a mistake in commit A and then made commit B. Now I can only amend B. So I do $ git reset --soft HEAD~1 I correct and re-commit A and then re-commit B.
Be careful, because you can’t always revert some of these undo.

Remove files from last commit

To remove one or more files from last commit, just move it outside git repository folder then amend last commit:

$ mv <file> /path/outside/git/folder/
$ git commit --amend

Aliases in git

Adding alias definitions using ~/.gitconfig. Here’s some that I often use:

[alias]
	clog = log --graph --pretty=format:'%ad %s | %an %h' --date=short
	vlog = log --graph --pretty=format:'%Cred%ad %Cblue%an%Cgreen%d %Creset%s %C(yellow)%h' --date=short
	graph = log --graph --all --pretty=format:'%Cred%h%Creset - %Cgreen(%cr)%Creset %s%C(yellow)%d%Creset' --abbrev-commit --date=relative
	a = !git add . && git status
	c = commit -a -m

You can add your own alias commands from the command line prompt:

$ git config alias.st status

Create a commit on behalf of someone else

When you apply a patch from someone else, you can give authority for him.

$ git commit -m "Commit Messages" --author="Someone Else "

Misc Git Hints, Tips, Tricks to Mastering Git, GitHub

Moving screen in diff

You can scroll the diff screen with Space to scroll down and w to scroll up.

Count commits by author

Ever wondered how many commits you’ve contributed to a project? With git shortlog is a nice way to find out.

Count Git commits
Count Git commits

The -s option squashes all of the commit messages into the number of commits, and the -n option sorts the list by number of commits. There’s a few other neat options: -e will append emails, and you can control columns widths with -w.

Pull/Update all repositories in subfolder

I stored all favorite projects as Git repositories in folder call Git-Sources, when I need the latest version of they, I use the command below:

$ cd repos
$ find . -maxdepth 1 -type d -exec sh -c '(cd {} && git pull)' ';'

Note: if the -depth 1 option is not available, try -mindepth 1 or -maxdepth 1.

You can use this tip to execute any command for all sub-folder as git repositories

Commit specified files or ignore files

Sometimes, after done the coding processes, you need commit only specified files with or ignore some files in changed files. Just done with these command:

$ git commit /path/to/specified/file1 /path/to/specified/file2 -m "Commit messages"

Remove files from last commited

Soft delete

If you only want to remove a file from your previous commit, and keep it on disk

$ git reset --soft HEAD^

You can use HEAD~1 instead HEAD^. Then reset the unwanted files in order to leave them out from the commit:

$ git reset HEAD path/to/unwanted_file

Now commit again.

Hard delete

If this is your last commit and you want to completely delete the file from your local and the remote repository, you can:

$ git rm <file>
$ git commit --amend

The amend flag tells git to commit again, but merge (not in the sense of merging two branches) this commit with the last commit.

Write Smart Commit Message

I wrote commit messages with summarize changes in around 50 characters or less, then I continue explain about the commit after blank line. Here is the seven rules of a great git commit message. Follow that guide and you will wished to know it before.

Change the URI (URL) for a remote Git repository

The easiest way to tweak this imo is to edit the .git/config file in your repository.
If you don’t want to change it manual by hand, you can change it through command line with:

$ git remote set-url origin <URL>

To be continued…

I’ll updating this post with most Helpful hints, tips and tricks to mastering Git ability. More to come …