git: useful commands

Examples of running git from the command line.

In the lab, we use git to keep track of our code.  All the code is hosted on a server called Github.

Basics

To run commands on a repository, first cd (change directory) to the folder where that repository lives.  You'll see the prompt change to add the word (master) after the directory name.
To check the status of the repository, e.g. whether there are any additions or changes to files in the directory, use git status:
git status
Even if git status says "Your branch is up to date with 'origin/master'", there may be changes upstream that your local machine doesn't know about. To pull in any of changes that may have been made to the repository from other machines, use git pull:
git pull
This will pull in any changes. If no changes were made to the central repository since the last pull, git will say "Already up to date."
It's a good idea to get to this state before you start editing code, since it can help you avoid conflicts with existing edits upstream.

Now, let's say you've made edits to the code. To take a snapshot (a "commit") of these changes, first stage each file whose changes you want to include by using git add:
git add <filename>
To add all files with changes at once, use:
git add .
(This is not recommended unless you double-check to make sure you want to add ALL files with changes and ALL new files -- i.e., everything that shows up in red text when you run git status!)

To commit the files you've added, use git commit:
git commit -m "Example commit message"
The commit message should be something descriptive of the changes you are committing.

You can make several commits in a single session; they will all be stored locally as individual snapshots of the code.  When you're ready to make the changes available to all other users/computers, use git push:
git push
This will incorporate all the local commits into the remote "origin" which lives on Github.com.

What if I try to do a git push, and I get an error?

This is likely caused by changes upstream that you haven't yet incorporated into your local copy. You need to incorporate these changes so that your own edits can be layered on top of them. First use git pull:
git pull
This will incorporate the remote changes. Then do a push and accept the default commit message ("Merge branch 'master' of https://github.com...").

What if I do a git pull, and I pull in changes I didn't want?

You can undo a git pull with git reset:
git reset --hard HEAD@{1}
This will put your working directory in the state it was in before the pull.