Checkout a Remote Branch in Local

$ git checkout --track origin/master

The above command creates a local branch with the same name, i.e. master, as the remote branch, and let the local branch track the remote one. “Tracking” means when run git push, Git knows where it pushes changes into.

Some notes from git checkout --help,

As a convenience, –track without -b implies branch creation

-t, –track
When creating a new branch, set up “upstream” configuration.

If no -b option is given, the name of the new branch will be derived from the remote-tracking branch

# Assume the Git tag is "0.1.0"
$ git rev-list -n 1 0.1.0 --pretty=format:"%h" | tail -1

The tag “0.1.0” points to the commit c363005. Use %H if the full SHA1 is needed.

(Search “placeholder” in git show --help for the document of format:<string>.)

Add --abbrev option, like --abbrev=8, if a fixed width SHA1 is needed.

Fix the ^M Character Shown in git diff Result

Sometimes, when run git diff, it prints ^M at the end of some lines. The ^M character represents a carriage-return character, i.e. CRLF, the new line character in Windows. You may see ^M before, if you use Vim to edit some files coming for Windows/DOS. Seeing ^M in the git diff result means the same line was ended with CRLF but now with LF, or vice versa.

Usually, a Git repository should be configured in a way that all text files committed into the repository end with LF, while files checked out end the local machine specific endings, i.e. LF in Unix and CRLF in Windows machines. So that ^M would not be seen in git diff. To fix a repository’s configuration, add a .gitattributes file with content like

# Set the default behavior, in case people don't have core.autocrlf set.
* text=auto

# Declare files that will always have CRLF line endings on checkout.
*.bat text eol=crlf

“Renormalize” all the files with updated configuration.

$ git stash -u
$ git add --renormalize .
$ git status
$ git commit -m "Normalize line endings"
$ git stash pop

See this GitHub doc, Configuring Git to handle line endings, for more details.

Prune stale remote branches in local repository

As time goes by, local repository may have many remote branches, which were actually deleted in remote repository. For example, in GitLab someone’s feature branch is usually deleted while it’s merged by a merge request. However, these origin/feat-x, origin/feat-y branches are kept in your local repository since they’re fetched.

To delete these stale remote branches in local all at once, run

$ git remote prune origin

# Or,
$ git fetch --prune

It’s said in git remote --help,

might even prune local tags that haven’t been pushed there.

So it’s a good idea to run above commands with --dry-run option first.

Delete one remote branch by git branch -r -d origin/feat-x.