2 April 2020

Helpful Git Commands

Useful Git commands for various situations.

Create a new local branch and switch to the new branch.

Create new branch

$ git checkout -b FeatureUpdateConfigurations
Switched to a new branch 'FeatureUpdateConfigurations'

Push a new local branch to the origin.

Push new branch

$ git push -u origin FeatureUpdateConfigurations
Enumerating objects: 31, done.
## Stuff Omitted
remote: Storing index... done (66 ms)
To ssh://none.yo.business.com:22/tfs/somdir/_git/MyProject
 * [new branch]      FeatureUpdateConfigurations -> FeatureUpdateConfigurationsInternalSite/CustomUpdate/InternalError.asp?site_name=webconnectlite&secure=1&error_code=13
Branch 'FeatureUpdateConfigurations' set up to track remote branch 'FeatureUpdateConfigurations' from 'origin'.

Various ways to commit

## Commit files/folders in the current working directory.
$ git commit . -m "Commit Message"
## Commit a specific file
$ git commit someFile -m "Commit Message"
## Commit more than one specific file
$ git commit someFile someOtherFile -m "Commit Message"
## Commit a specific file and a specific directory
$ git commit someFile someDir/ -m "Commit Message"

Various Ways to Show Status

## Show status for whole branch
$ git status
## Show status for current working directory
$ git status .
## Show files staged for commit
$ git diff --name-only --cached

You run “git pull” and automatic merge fails. You just want to revert to the origin.

Revert local Git to origin

$ git fetch origin
$ git reset --hard origin/master
HEAD is now at c1ebe74 Merged PR 34: gitignore change

Remove all files not in Git. Can be used post revert to origin above to remove all non commited files.

Remove files not in Git.

$ git clean -xdf
Removing someDir/
Removing someOtherDir/someFile1.txt
Removing someOtherDir/someFile2.txt

List branches that are on origin but not your local Git.

List Local and Remote Branches

$ git branch -r

Delete Remote and Local Branches

$ git push -d origin BranchName
$ git branch -d BranchName
$ git branch -D BranchName

Prune Branches Not in Origin

$ git remote prune origin

How to resolve merge conflicts

Steps to Resolve Merge Conflict

## 1 Checkout the branch with conflict.
$ git checkout branchName
## The conflict exists because the master was updated after you branched.
## So we will "rebase" our branch on the master as it is now.
$ git pull --rebase origin master
## Now edit the files that are conflicted to what they should be.
## Be sure and remove conflict markers:  <<<<<<<, =======, >>>>>>>
## Now add the files that you edited.
$ git add conflictedFile
$ git commit conflictedFile -m "Commit Message"
## Now that the conflicts are resolved continue rebase.
$ git rebase --continue
## Finish by pulling and pushing
$ git push origin +branchName
tags: linux - git

Less Is More