Skip to content

Instantly share code, notes, and snippets.

@yellowbyte
Last active December 24, 2021 09:08
Show Gist options
  • Save yellowbyte/71446a000e3fbc0f8b7aa060060e1b84 to your computer and use it in GitHub Desktop.
Save yellowbyte/71446a000e3fbc0f8b7aa060060e1b84 to your computer and use it in GitHub Desktop.
useful but easily forgotten git commands

add: Add file contents to the index

  • Stage files with confirmation (commit only part of a file)
    • git add --patch (git add -p)

branch: List, create, or delete branches

  • Delete local branch if it has already been fully merged in its upstream branch
    • git branch -d <branch_name>
  • Delete local branch, irrespective of its merged status
    • git branch -D <branch_name>

checkout: Switch branches or restore working tree files

  • Bringing files from another branch or commit to current branch
    • git checkout <commit_hash> <relative_path_to_file_or_dir>
    • git checkout <remote_name>/<branch_name> <file_or_dir>

push: Update remote refs

  • Delete remote branch
    • git push <remote_name> --delete <branch_name>
      • git push origin --delete <branch_name>

reset: Reset current HEAD to the specified state

  • Reset local repository branch to be just like remote repository HEAD
    • git fetch origin; git reset --hard origin/<branch>
  • Undo staging (git add <filename>)
    • git reset <filename>
  • Undo all staged files
    • git reset
  • Undo last local commit
    • While preserving local changes: git reset --soft HEAD~1
    • Without preserving local changes: git reset --hard HEAD~1

rebase: Reapply commits on top of another base tip

  • Combining/squashing multiple commits into one (change pick to squash for the commits you want to squash)
    • git rebase -i HEAD~<numbers of commits to look back>
    • git rebase -i
  • Rebase changes in branch 2 on top of main branch (for smooth PR)
    • git rebase main

rm: remove file(s) from working tree and index

  • Stop tracking a file
    • git rm --cached <file>
  • Stop tracking a folder
    • git rm -r --cached <folder>

show: Show various types of objects (blobs, trees, tags, and commits)

  • Look at file in a different branch while staying in current branch
    • git show <branch_name>:</path/to/file>
    • git show <branch_name>:</path/to/file> | vim -
  • Show what was changed in a commit
    • git show <COMMIT_HASH>

switch: switch to the specified branch

  • Undo changes and return to previous branch. Useful if you are experimenting in detached state
    • git switch -
  • Keep changes you made in detached state and create a branch for it
    • git switch -c <new branch name>

rev-parse: pick out and massage parameters

  • Get current commit hash
    • git rev-parse HEAD
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment