Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Git basics (for CS 189)

Git basics

See the full git documentation

Set up a repository from scratch

Do this if you have an empty repository on Github.

  • Create a new repository on your machine (in an existing folder): git init
  • Add your empty GitHub repository as a remote: git remote add origin[REPO-NAME].git
  • Move on to "Basic use"

Clone an existing repository

Do this if you want to start a local copy of a GitHub repository that already has stuff in it.

  • Clone the existing repo: git clone[REPO-NAME].git
  • Move on to "Basic use"

Basic use

Before you start making changes locally, make sure you have the latest version of the repository with git pull.

  • Check the status of changes in your repository: git status
  • Add files/changes to commit:
    • Add all files and changes: git add .
    • Add only changes to files that you're already tracking with git: git add -u
    • Add a single file or folder: git add [MY-FILE]
  • Commit your changes: git commit -m "[YOUR COMMIT MESSAGE]"
  • Push your changes to GitHub: git push origin master
  • push will fail if someone else made changes since your last commit. To push your own changes, you will first need to pull these changes. In simple cases, git will be able to automatically merge the differences between the two automatically.
    • Pull the remote changes: git pull
    • Deal with any merging. (This is trickier if it can't happen automatically.)
    • Push your newly merged version: git push origin master

Switching to an old version of your repository

We will grade the last version of your repository pushed before the deadline. If you have changes that aren't working, you may want us to see/use an older version of your repository.

A better way of handling things to prevent this issue is to use branches, and only commit each fully working version to the master branch of your repository.

  • Get the hash of the commit you wish to use: git log
  • Revert the status of your repository to that commit: git revert --no-commit [YOUR-HASH]..HEAD
  • Commit that version: git commit (and then push to GitHub)

This is a safe way to do it, because you will not undo (remove from history) any commits in between your current version and the version you're switching to. If your later want to return to this version, you can simply get the hash for it and follow the same procedure. (From StackOverflow)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.