Skip to content

Instantly share code, notes, and snippets.

@HenokT
Last active December 21, 2021 14:45
Show Gist options
  • Save HenokT/519b7d57c9841f190dbe to your computer and use it in GitHub Desktop.
Save HenokT/519b7d57c9841f190dbe to your computer and use it in GitHub Desktop.

Useful git commands

  • Sort branches by committerdate (DESC)

    git branch --sort=-committerdate

  • push local branch to remote and setup the local branch to track remote branch

    git push -u origin <branch>

  • delete local branch

    git branch -d <branch>

  • delete remote branch

    git push origin --delete <branch>

  • delete references to stale remote branches.

    git remote prune origin

    Add --dry-run to see what gets pruned before without pruning anything.

  • delete merged branches (whose tips are reachable from HEAD)

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

  • delete squash merged branches (whose tips are not reachable from the the HEAD)

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

  • revert changes made in a specific commit by applying a new commit

    git revert <commit> --no-commit

    or

    git revert <commit> -n

  • Reset staging area to match most recent commit, but leave the working directory unchanged.

    git reset

  • Reset staging area and working directory to match most recent commit and overwrites all changes in the working directory.

    git reset --hard

  • Add desired commit(s) from any branches git cherry-pick <SHA-1>...<SHA-1> --no-commit

  • Adding a submodule

    git submodule add <url-to-repo>
    git add .gitmodules <name>
    git commit -m <message>
    
  • Cloning a repo with submodules

    git clone --recursive /url/to/repo/with/submodules
    

    or if you already cloned it without --recursive option, do this

    git clone /url/to/repo/with/submodules
    
    # update the local .git/config with the mapping from the .gitmodules file.
    # it can accept a list of explicit module names if only specific submodules 
    # that are needed for work on the repository
    git submodule init
    
    # fetch all the data from the submodule project and check out the mapped commit 
    # in the parent project.
    git submodule update
    
  • print log to see loc committed by a committer since date

    git log --since="2015-12-29" --author="<author name>" --pretty=tformat: --numstat | awk '{ add += $1; subs += $2; loc += $1 - $2 } END { printf "added lines: %s, removed lines: %s, total lines: %s\n", add, subs, loc }'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment