Skip to content

Instantly share code, notes, and snippets.

@puncoz
Last active February 16, 2021 02:16
Show Gist options
  • Save puncoz/46c8ab0075c3c7c919821b68d674c8d4 to your computer and use it in GitHub Desktop.
Save puncoz/46c8ab0075c3c7c919821b68d674c8d4 to your computer and use it in GitHub Desktop.
Useful git commands

Useful git commands

Get local branch count

git branch | wc -l

Delete all merged branch from local

git branch --merged | egrep -v "(^\*|master|dev)" | xargs git branch -d

Update only date time of last commit

git commit --amend --date="$(date -R)"

This will trigger a git commit --amend action

Update author info on last commit

git commit --amend --author="Puncoz Nepal <info@puncoz.com>"

This will trigger a git commit --amend action

View git configs

gcf This works on ZSH shell

To count the commits

for the branch you are on:

git rev-list --count HEAD

for a branch

git rev-list --count <branch-name>

If you want to count the commits on a branch that are made since you created the branch

git rev-list --count HEAD ^<branch-name>

Squash

git rebase -i HEAD~5

Untrack files from git

git rm -r --cached <file>
git add -u

Switch Branch

git checkout <branch-name>

or,

git switch <branch-name>

Restore changes

git checkout <path-to-file>

or,

git restore <path-to-file>

Clean untracked files/directories

For files

$ git clean -f

For Directories

$ git clean -d

Rename branch

1. Rename your local branch.

If you are on the branch you want to rename:

git branch -m new-name

If you are on a different branch:

git branch -m old-name new-name

2. Delete the old-name remote branch and push the new-name local branch.

git push origin :old-name new-name

3. Reset the upstream branch for the new-name local branch.

Switch to the branch and then:

git push origin -u new-name

Summarize git log output

git shortlog -s -n

Migrate repository from one repo to another

// Fetching all branches and tags from old repo
git branch -r | grep -v '\->' | while read remote; do git branch --track "${remote#origin/}" "$remote"; done
git fetch --all`
git pull --all

// Pushing into new repo with remote name new-repo
git push -u new-repo --all
git push -u new-repo --tags

.gitignore all the .DS_Store files in every folder and subfolder

Remove the existing files using this command

find . -name .DS_Store -print0 | xargs -0 git rm -f --ignore-unmatch

Add .DS_Store in your .gitignore file

Commit your changes in .gitignore

git add .gitignore 
git commit -m "removed .DS_Store"

See current branch commit hash

git rev-parse HEAD

or,

git rev-parse --verify HEAD

Get commit messages from last tag to current

git log $(git describe --tags --abbrev=0)..HEAD --pretty=format:"%s" --no-merges

Git force push with safe

git push --force-with-lease
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment