

















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


















This self-paced tutorial will take you through the basic use of Git and GitHub. These are systems that allow you to maintain code and work that you are doing, track changes, recover old versions and collaborate with other people. There are many tutorials available on the Web or in books. I use this style for com- mands you type, and this style for filenames. In places I use this style or THIS STYLE for things that should be substituted with an appropriate filename or word.
1 Introduction — what are Git and GitHub? 2
2 Installing Git 3 2.1 If you are using Linux............................... 3 2.2 If you are using a Mac............................... 3 2.3 If you are using Windows............................. 3
3 Getting started on GitHub 3
4 Configuring Git 5
5 Creating a Git repository 5
6 Creating and editing files 6
7 Adding files to your Git repository 7
8 Finding out what’s happening 7
9 Making changes and tracking them 8
10 Synchronizing your local Git repository with GitHub 9
11 Deleting and renaming files 10
12 Undoing changes 10 12.1 Before you commit................................. 10 12.2 After you commit.................................. 11 12.3 Being more selective.............................. 12 12.4 Retrieving an old version............................ 13
13 Branching 13 13.1 Checking differences between branches................... 14 13.2 Merging branches................................ 15 13.3 Deleting branches................................ 15
14 Tags and releases 16 14.1 Summarizing your changes.......................... 17
15 Downloading a repository 17
16 Managing multiple copies of a repository 18 16.1 Dealing with simple conflicts......................... 18 16.2 Dealing with more complex conflicts..................... 20
17 Summary 22
18 Command summary 23 18.1 Creating a local git repository......................... 23 18.2 Synchronizing your local repository with GitHub............. 23 18.3 Changing and adding files........................... 23 18.4 Looking at differences............................. 23 18.5 Check out a repository from GitHub..................... 24 18.6 Creating branches for developing and testing new features........ 24 18.7 Undoing changes................................ 24 18.8 Tags and releases................................ 25
19 Other tutorials 25
1 Introduction — what are Git and GitHub?
How many times have you written a document — an essay perhaps — where you think you have got to your final version and called it EssayFinal, only to read through it again and spot some errors, so you rename it EssayFinal2. Perhaps it’s a disserta- tion and you give it to your supervisor who has some comments so you end up with EssayFinalRevised. Perhaps you now realise it’s too long so delete some stuff and create EssayFinalRevisedCut. Then you read it again and realise that you really need to add something back from an earlier version as it no longer makes sense — Oh! Wait... Did you keep that earlier version? Git is designed to deal with exactly this sort of situation. Unfortunately it doesn’t work that well with ‘binary’ files like the .doc or .docx files that Word uses, but for plain text files of the sort you use for writing programs and scripts, or files that you use with LaTeX (the typesetting system used to write these tutorials), it removes these
Task: Go to www.github.com and create an account. You probably want to select a fairly memorable (and sensible!) user name — ideally this is something that you will continue to use throughout your career.
As explained in the Introduction, one of the main things you will want to do with GitHub is synchronize your local repository with it. GitHub requires you to log in with your username and password. This would be rather a nuisance if everytime you wanted to synchronize your local Git repository with GitHub you had to specify your username and password. Fortunately a mechanism is provided to allow you to avoid this^1. First you need to create yourself what is known as an SSH key:
1: Type the following:
cd mkdir .ssh cd .ssh ssh-keygen
ssh-keygen will probably ask you where you want to save the key. Simply press the Return key to accept the default. ssh-keygen will then ask you to enter a passphrase. Simply press the Return key so that no passphrase is generated. You will then have to press the Return key a second time to confirm your (empty) passphrase. Now if you type ls , you should find that you have two files called id_rsa (your private key) and id_rsa.pub (your public key). Display your public key:
2: Type the following:
cat id_rsa.pub
(^1) This relies on using a public/private key pair for authentication. This is the same sort of thing that is done for encrypting your bank details when you send them over the web. Take a look at en. wikipedia.org/wiki/Public-key_cryptography if you want to know more
Task:
pbcopy < ~/.ssh/id_rsa.pub
to get the public key into your clipboard so you can paste it into GitHub.
4 Configuring Git
You need to type two lines to configure Git and link it to GitHub. In the following commands:
3: Type the following:
git config --global user.name "USERNAME" git config --global user.email "EMAIL"
5 Creating a Git repository
When you use Git, you create one repository for each program or project that you work on. I suggest that you create all your Git repositories under a single directory called git. Let’s start by creating this directory:
4: Type the following:
mkdir ~/git
When you are done press the Esc key to return to command mode. To exit the editor, press Esc to ensure you are in command mode, then type :wq Table 1 summarizes the most useful commands.
7 Adding files to your Git repository
Let’s start by creating a file to contain some information about proteins.
Task: Use a text editor to create a file in your ∼/git/GitExercise/ directory called proteins.txt containing the following text:
Lysozyme Chicken LYSC_CHICK P Lysozyme Human LYSC_HUMAN P Hemoglobin-alpha Human HBA_HUMAN P Hemoglobin-beta Human HBB_HUMAN P
Exit your editor and tell Git that you want to track this file:
7: Type the following:
git add proteins.txt
You only need to do this when you have a new file that you want to track with Git. Having specified that the file should be tracked, we need to tell Git that we have made changes to the file that we want it to record:
8: Type the following:
git commit -a -m "Initial version"
Strictly in this case the -a isn’t needed, but it will be whenever you do this in future so we will put it in^3. The -m specifies the text that follows in double-inverted commas is a comment (or m essage) briefly explaining what changes were made in this version. If you forget to supply a message with -m then you will enter the ( vim ) where you can enter text (See the notes above).
8 Finding out what’s happening
To find out whether there are any files that are not being tracked by Git or whether there are files that are being tracked that haven’t been committed:
9: Type the following:
git status
(^3) The -a tells Git to add the changes in this file to those that are being tracked by commit. You
already did that with git add which is always needed for a new file.
Having just committed your changes, you should receive the message:
On branch master nothing to commit, working directory clean
Let’s create another file that isn’t being tracked just to see what happens:
10: Type the following:
touch foo.txt git status
The touch command is used to set the date and time on a file to the current date and time. If the file doesn’t exist, it creates it, so we are just using this to create an empty file. This time the output from git status should look something like:
On branch master Untracked files: (use "git add ..." to include in what will be committed)
foo.txt
nothing added to commit but untracked files present (use "git add" to track)
Git warns you that there are files present that aren’t being tracked. Since we only created this file as a test, let’s delete it again:
11: Type the following:
rm foo.txt
We can also list what commits have been made:
12: Type the following:
git log
This will list all the commits you have made with the comments that you specified with -m. The commit line in the output will be followed by a random string of char- acters — something like b5526a8ddb40925e01620e751ecc97b735464444. Don’t worry about this for now; you will find out why it is useful in a minute.
9 Making changes and tracking them
Task: Edit your proteins.txt file by adding a couple of extra lines to the end of the file. For example:
PFKM Human PFKAM_HUMAN P Pfkm Mouse PFKAM_MOUSE P
Task: Refresh the GitHub web page — you should now find that your proteins.txt file is listed on the page. You should also see that there have been 2 commits reflecting what you did on the command line.
From now on, after you make and commit changes, all you need to do is git push (without the -u origin master ) to ‘push’ your changes onto GitHub.
11 Deleting and renaming files
Normally you would delete a file with rm and rename or move a file using mv. How- ever, we also need to tell Git that we have deleted, renamed or moved a file. To do that we have to remember to delete, rename or move the file via Git. Do not do this now , but if, for example, we wished to rename our proteins.txt file to proteininfo.txt we would do: git mv proteins.txt proteininfo.txt Similarly to delete a file and stop Git from tracking it we would do: git rm proteins.txt
12 Undoing changes
Let’s add something else to the proteins.txt file, but something that was clearly a mistake.
Task: Edit the proteins.txt file and add the following line to the end of the file:
This is clearly a mistake!
If you now type git status you will be told that the file has been changed, but that you haven’t committed the changes yet. At this stage, you can go back to the version without the changes:
16: Type the following:
git checkout -- proteins.txt cat proteins.txt
As you will see, the file has reverted back to what it was before you added the lines. If you have modified more than one file and want to reset everything to the last commit, you can also do git reset --hard to reset all the files.
Suppose however that you have committed a change and now want to undo that change and revert to the previous version. You will recall that when you use git log you are shown the comments, but also shown lines saying commit with some appar- ently random set of letters and numbers. This is an identifier for a particular commit. We can use git revert with one of these identifiers to remove the changhed that happened in that commit. In practice, you only need about the first 6 or 7 characters of the commit identifier to identify a particular commit uniquely. Again add something to the proteins.txt file that we will clearly wish to undo.
Task: Edit the proteins.txt file and add the following line to the end of the file:
This is clearly another mistake!
Now commit the change and look at the Git log:
17: Type the following:
git commit -a -m "I added a mistake on purpose" git log
Task: Record the first 6 or 7 characters of most recent commit message (at the top of the log) which is associated with the erroneous commit.
For example, my Git log looks something like:
commit adbd940940ba3f1584d3bd77c4b048e2b0fcda3f Author: AndrewCRMartin Date: Thu Sep 28 12:39:37 2017 +
I added a mistake on purpose
commit 54f0e41a1c772dbde9002ab1252c634c6296ec Author: AndrewCRMartin
To obtain an older version of a particular file, you can use the command: git checkout commitid -- filename where commitid is the commit identifier of the version that we want to keep (i.e. the commit containing the last good version of the file) and filename is the filename of the file you want to obtain. Having done this you would also need to commit the changes in the usual way with git commit.
To get back to an older version in the log history without actually undoing the changes between that version and the current version, we use the git checkout commitid command where commitid is the commit identifier of the version that you want to go back to. You can then create a new branch starting from that point (see Section 13, below). To return to the latest commit, simply type git checkout master.
Task: Give it a try. Go back to the original commit, take a look at the proteins.txt file and then return to the latest version.
13 Branching
Often we find that we have a version of a program (or script) that we are happy with, but we want to add some new feature(s). Whenever we make changes we risk break- ing the existing version. Git allows us to create experimental ‘branches’ where we can develop new features before merging them back into the master repository. This is also useful when we have multiple people working on a project. Each per- son creates a branch for the feature or bug-fix they are working on and when they are finished they merge it back into the master branch. Suppose we want to modify our proteins file to include the length of each protein. Adding that extra field to the file might well break some program that relied on the file, so we will do it in a new branch called ‘protlength’. We create a new branch using git checkout -b branchname (where -b tells checkout to create a new branch):
20: Type the following:
git checkout -b protlength
This has created a new branch and switched to using that branch. You can confirm which branch you are currently using:
21: Type the following:
git branch
The ‘master’ branch is the default branch that we were using previously. If we are using GitHub, we need to tell Git to link this new branch to GitHub. We do this with the command^5 :
22: Type the following:
git push -u origin protlength
We can now make our experimental changes to proteins.txt.
Task: Edit proteins.txt to add the protein lengths:
Lysozyme Chicken LYSC_CHICK P00698 147 Lysozyme Human LYSC_HUMAN P61626 148 Hemoglobin-alpha Human HBA_HUMAN P69905 142 Hemoglobin-beta Human HBB_HUMAN P68871 147 PFKM Human PFKAM_HUMAN P08237 780 Pfkm Mouse PFKAM_MOUSE P47857 780
Once we have made our changes, we commit them and push them to GitHub:
23: Type the following:
git commit -a -m "Added protein lengths" git push
If we wish to return to the ‘master’ branch we can do so with:
24: Type the following:
git checkout master
Now take a look at proteins.txt — you will see that it no longer has the protein lengths. Return to the ‘protlength’ branch:
25: Type the following:
git checkout protlength
and verify that proteins.txt now has the protein length information.
Just as we can use diff to look at the differences between files, we can use git diff to look at differences between branches or commits:
(^5) You may remember that when you first synchronized with GitHub you had to type
git push -u origin master. That was telling Git to link the ‘master’ branch with a server called ‘origin’ which is the GitHub web site (we specified that in Section 10 with git remote add origin ; now we are synchronizing a different branch with ‘origin’.
30: Type the following:
git push origin --delete protlength git remote prune origin
14 Tags and releases
We have already encountered the rather long-winded identifiers that are used to la- bel particular commits. However it would be much nicer for particular versions — perhaps those that we release to other people or those that we have used for the anal- ysis that we publish in a paper — to be able to tag them with a much simpler label, typically a version number. When we have a particular version checked out, we can tag it as follows:
31: Type the following:
git tag v1. git push --tags
The first command specifies the tag that you wish to use for this version. You can choose whatever tag you like, but ‘v1.0’ is probably a sensible option. The second command makes sure that GitHub knows about the tag too. On GitHub, we can then create a ‘release’ of our repository. A release provides a ZIP file and a gzipped tar file that people can download. To do this, follow these steps:
GitHub will now return to the releases page which provides links where you can download the code as a ZIP file or gzipped tar file^6.
(^6) Note that these are not Git repositories, they are simply copies of the files as present in that tagged
commit.
The git shortlog command gives you the commit messages (the comments you provided with the -m option to git commit ) without all the other information:
32: Type the following:
git shortlog
You can also obtain only the commit messages between two particular commits: git shortlog commitid1..commitid The version that you have currently checked out can be abbreviated as HEAD so to find the changes between a particular commit and the current version, you can use: git shortlog commitid..HEAD
As usual tags are abbreviated ways of accessing commit identifiers, so if you have created a tag for a particular version, you can use the tag name instead of the commit identifier: git shortlog tag..HEAD
Consequently, when you create a new release (say ‘v1.1’), you can obtain the changes from the previous release (say ‘v1.0’) with: git shortlog v1.0..HEAD
15 Downloading a repository
You are now going to download a second copy of your repository from GitHub. Nor- mally this is unlikely to be something you would want to do on the same computer. However, it is quite possible that you might have a copy of the repository on your laptop and another on a desktop computer — actually this is a really useful way of synchronizing and tracking changes across multiple machines keeping a backup on the cloud at the same time. Personally I do this to synchronize my laptop, my desktop at home and my machine at UCL. It is also possible that you might want to collaborate with someone else such that you would have a copy and someone else would have a copy. Let’s start by creating a git2 folder that we can put the copy in (again you wouldn’t normally do this; we are just pretending this is on another machine). Start by creating a directory for your second copy:
33: Type the following:
mkdir ~/git
Now we will ‘clone’ the repository so we have a second local copy in this other directory. Replace USERNAME with your GitHub username in the following:
34: Type the following:
cd ~/git git clone [email protected]:USERNAME/GitExercise.git
You should find that you now have a GitExercise directory exactly as you had before.
Task: Edit the file proteins.txt and add the following line to the start of the file:
Lysozyme Mouse LYZ1_MOUSE P17897 148
Now commit the changes and push them to GitHub:
40: Type the following:
git commit -a -m "Added mouse lysozyme" git push
Now we will add a line to the end of proteins.txt in the second repository:
41: Type the following:
cd ~/git2/GitExercise
Task: Edit the file proteins.txt and add the following line to the end of the file:
PFKM Rat PFKAM_RAT P47858 780
Now commit the changes and try to push them to GitHub:
42: Type the following:
git commit -a -m "Added rat PFK" git push
You will find that Git refuses to push the changes to GitHub because the version of the repository on GitHub has changed since you last synchronized. You should see a message like:
To [email protected]:USERNAME/GitExercise.git ! [rejected] master -> master (fetch first) error: failed to push some refs to ’[email protected]:USERNAME/GitExercise.git’ hint: Updates were rejected because the remote contains work that you do hint: not have locally. This is usually caused by another repository pushing hint: to the same ref. You may want to first integrate the remote changes hint: (e.g., ’git pull ...’) before pushing again. hint: See the ’Note about fast-forwards’ in ’git push --help’ for details.
Instead you must pull down the changes to merge them with what you have done before you can push:
43: Type the following:
git pull
This will automatically merge the changes on GitHub with the changes you have made locally. The screen will change to a message saying something like:
Merge branch ’master’ of github.com:USERNAME/GitExercise
(Your message may be somewhat different on non-Linux systems.) Again this has taken us to an editor where we can add information, but we will simply accept the default message by typing the characters: :wq (colon, ‘w’, and ‘q’). Now you can take a look at the proteins.txt file and you should find both sets of changes have been included in the file. We should now be able to push the changes to GitHub:
44: Type the following: git push
Before we continue, we will go to the other repository and pull down the merged changes:
45: Type the following:
cd ~/git/GitExercise git pull
Both versions of the repository are now back in synchronization!
As we have seen, Git sorts out conflicts when they are in different parts of a file. How- ever, when two repositories have a different change to the same line of a file, Git cannot sort it out automatically. Let’s try making a change to the same line in both versions of the file. First we will change the file in ∼/git: 46: Type the following:
cd ~/git/GitExercise
Task: Edit the proteins.txt file and change the line
Hemoglobin-alpha Human HBA_HUMAN P69905 142
to read
Hemoglobin-alpha HUMAN HBA_HUMAN P69905 142
(it doesn’t really matter what change you make — just change something!)