Git Base Commands

Cheatsheet

Commits

  • Get the files in a commit git checkout
  • Get difference from parent git show
  • Merge with another commit git merge
  • Look at parents git log

Staging

Note

git diff only shows the difference in unstaged files and git commit -a does not add new files that are untracked

  • See all changes that have yet to be committed git diff HEAD
  • See all staged changes git git diff --cached

Branches

Branches consist of three things

  1. A name (such as main, development, or a particular feature)
  2. The latest commit
  3. A reflog that shows how the branch has changed over time

To remove commits from a branch use git reset

The branch should be setup to display in the command prompt, or somewhere else within the development environment to reduce the risk of forgetting which branch you are commiting to.

The current branch is stored in .git/HEAD, and will either be a branch name, or a commit hash if you are in a detached HEAD state.

Detached HEAD States

You can end up in this state through three mechanisms, tag, tracking a remote branch, or checking out a particular commit of a remote.

Tip

To avoid losing any changes made while in this state, just create a new branch using git checkout -b new_branch_name

Merges

There are three mechanisms for a merge:

  1. Rebase
  2. Merge
  3. Squash

The biggest difference is that rebase will not create merge commits, while merge will. Squash is useful to combine multiple commits into one.

Remote

The remote can be any repository that is pulled/pushed from. It is usually hosted on a platform like GitHub or Codeberg. The configuration for the remote is stored in .gitconfig for the repository and consists of a name and url.

[remote 'origin']
url = "https://codeberg.org/mark-pitblado/notes.git"

Tip

Adding push.autoSetupRemote = True within .gitconfig will enable new branches to automatically be tracked once pushed.

Fix Diverged Remotes

  1. Combine the changes through a merge mechanism covered above
  2. Destroy local changes.
    git switch main
    git reset --hard origin/main
    
  3. Throw away remote changes: git push --force

Undoing

git reset can be used to undo things.