git commands

Branch

Change branch

# Using checkout command
git checkout <branch>
git checkout -b <new_branch>
git checkout <commit> # To get into detached head commit
 
# Using switch command
git switch <branch>
git switch -c <new-branch> # -c or --create
git switch --detach <commit>

Get file from another branch

# Using checkout command
git checkout <branch> [--] <filepath>
 
# Using restore command
git restore -s <branch> [--] <filepath> # -s or --source

Common commands

git reflog show

Get git url of remote repo

git remote get-url origin
git remote show origin
git config --get remote.origin.url

Search commit by commit message

git log --grep="Updated"

Clean/Undo changes

Undo local commit

# Revert commit but changes are not lost
# it has --soft flag implicitly
git reset HEAD~1
 
# Revert changes and also remove any working directory changes
git reset --hard

Clean working directory

git reset --hard # removes staged and working directory changes
git clean -f -d # remove untracked
git clean -f -x -d # CAUTION: as above but removes ignored files like config.
git clean -fxd :/ # CAUTION: as above, but cleans untracked and ignored files through the entire repo (without ":/", the operation affects only the current directory)

Diff

Diff branches

# show changes inside all files
git diff branch1 branch2
 
# show only filenames
git diff branch1 branch2 --name-only
 
# diff commits
git diff <commit-id1> <commit-id2>

Diff Files

git diff --no-index <path1> <path2>
 
# ignore whitespace and make it more useful
git diff --no-index --ignore-space-at-eol -b -w --ignore-blank-lines <path1> <path2>
  • If the diff is large spacebar can be used to go to next page faster

Cherry pick

  • applies changes introduced from a particular commit in the current branch
git cherry-pick <commit-id> 

Check the current status

git status
 
# include ignored changes in the output
git status --ignored

Merge Conflicts

Check merge conflicts

# show unmerged paths
git status
 
# show files with conflict marker
git diff --check