Linux "gitcore-tutorial" Command Line Options and Examples
A Git core tutorial for developers

This tutorial explains how to use the "core" Git commands to set up and work with a Git repository. If you just need to use Git as a revision control system you may prefer to start with "A Tutorial Introduction to Git" (gittutorial(7)) or the Git User Manual[1]. However, an understanding of these low-level tools can be helpful if you want to understand Git’s internals.


Usage:

git *






Command Line Options:

--stdin,
TAGGING A VERSIONIn Git, there are two kinds of tags, a "light" one, and an "annotated tag".A "light" tag is technically nothing more than a branch, except we put it in the .git/refs/tags/ subdirectory instead of calling it ahead. So the simplest form of tag involves nothing more than$ git tag my-first-tagwhich just writes the current HEAD into the .git/refs/tags/my-first-tag file, after which point you can then use this symbolic namefor that particular state. You can, for example, do$ git diff my-first-tagto diff your current state against that tag which at this point will obviously be an empty diff, but if you continue to develop andcommit stuff, you can use your tag as an "anchor-point" to see what has changed since you tagged it.An "annotated tag" is actually a real Git object, and contains not only a pointer to the state you want to tag, but also a small tagname and message, along with optionally a PGP signature that says that yes, you really did that tag. You create these annotated tagswith either the -a or -s flag to git tag:$ git tag -s <tagname>which will sign the current HEAD (but you can also give it another argument that specifies the thing to tag, e.g., you could havetagged the current mybranch point by using git tag <tagname> mybranch).You normally only do signed tags for major releases or things like that, while the light-weight tags are useful for any marking youwant to do — any time you decide that you want to remember a certain point, just create a private tag for it, and you have a nicesymbolic name for the state at that point.COPYING REPOSITORIESGit repositories are normally totally self-sufficient and relocatable. Unlike CVS, for example, there is no separate notion of"repository" and "working tree". A Git repository normally is the working tree, with the local Git information hidden in the .gitsubdirectory. There is nothing else. What you see is what you got.NoteYou can tell Git to split the Git internal information from the directory that it tracks, but we’ll ignore that for now: it’s nothow normal projects work, and it’s really only meant for special uses. So the mental model of "the Git information is always tieddirectly to the working tree that it describes" may not be technically 100% accurate, but it’s a good model for all normal use.This has two implications:· if you grow bored with the tutorial repository you created (or you’ve made a mistake and want to start all over), you can just dosimple$ rm -rf git-tutorialand it will be gone. There’s no external repository, and there’s no history outside the project you created.· if you want to move or duplicate a Git repository, you can do so. There is git clone command, but if all you want to do is justto create a copy of your repository (with all the full history that went along with it), you can do so with a regular cp -agit-tutorial new-git-tutorial.Note that when you’ve moved or copied a Git repository, your Git index file (which caches various information, notably some ofthe "stat" information for the files involved) will likely need to be refreshed. So after you do a cp -a to create a new copy,you’ll want to do$ git update-index --refreshin the new repository to make sure that the index file is up to date.Note that the second point is true even across machines. You can duplicate a remote Git repository with any regular copy mechanism,be it scp, rsync or wget.When copying a remote repository, you’ll want to at a minimum update the index cache when you do this, and especially with otherpeoples' repositories you often want to make sure that the index cache is in some known state (you don’t know what they’ve done andnot yet checked in), so usually you’ll precede the git update-index with a$ git read-tree --reset HEAD$ git update-index --refreshwhich will force a total index re-build from the tree pointed to by HEAD. It resets the index contents to HEAD, and then the gitupdate-index makes sure to match up all index entries with the checked-out files. If the original repository had uncommitted changesin its working tree, git update-index --refresh notices them and tells you they need to be updated.The above can also be written as simply$ git resetand in fact a lot of the common Git command combinations can be scripted with the git xyz interfaces. You can learn things by justlooking at what the various git scripts do. For example, git reset used to be the above two lines implemented in git reset, but somethings like git status and git commit are slightly more complex scripts around the basic Git commands.Many (most?) public remote repositories will not contain any of the checked out files or even an index file, and will only containthe actual core Git files. Such a repository usually doesn’t even have the .git subdirectory, but has all the Git files directly inthe repository.To create your own local live copy of such a "raw" Git repository, you’d first create your own subdirectory for the project, and thencopy the raw repository contents into the .git directory. For example, to create your own copy of the Git repository, you’d do thefollowing$ mkdir my-git$ cd my-git$ rsync -rL rsync://rsync.kernel.org/pub/scm/git/git.git/ .gitfollowed by$ git read-tree HEADto populate the index. However, now you have populated the index, and you have all the Git internal files, but you will notice thatyou don’t actually have any of the working tree files to work on. To get those, you’d check them out with$ git checkout-index -u -awhere the -u flag means that you want the checkout to keep the index up to date (so that you don’t have to refresh it afterward), andthe -a flag means "check out all files" (if you have a stale copy or an older version of a checked out tree you may also need to addthe -f flag first, to tell git checkout-index to force overwriting of any old files).Again, this can all be simplified with$ git clone git://git.kernel.org/pub/scm/git/git.git/ my-git$ cd my-git$ git checkoutwhich will end up doing all of the above for you.You have now successfully copied somebody else’s (mine) remote repository, and checked it out.CREATING A NEW BRANCHBranches in Git are really nothing more than pointers into the Git object database from within the .git/refs/ subdirectory, and as wealready discussed, the HEAD branch is nothing but a symlink to one of these object pointers.You can at any time create a new branch by just picking an arbitrary point in the project history, and just writing the SHA-1 name ofthat object into a file under .git/refs/heads/. You can use any filename you want (and indeed, subdirectories), but the convention isthat the "normal" branch is called master. That’s just a convention, though, and nothing enforces it.To show that as an example, let’s go back to the git-tutorial repository we used earlier, and create a branch in it. You do that bysimply just saying that you want to check out a new branch:$ git checkout -b mybranchwill create a new branch based at the current HEAD position, and switch to it.NoteIf you make the decision to start your new branch at some other point in the history than the current HEAD, you can do so by justtelling git checkout what the base of the checkout would be. In other words, if you have an earlier tag or branch, you’d just do$ git checkout -b mybranch earlier-commitand it would create the new branch mybranch at the earlier commit, and check out the state at that time.You can always just jump back to your original master branch by doing$ git checkout master(or any other branch-name, for that matter) and if you forget which branch you happen to be on, a simple$ cat .git/HEADwill tell you where it’s pointing. To get the list of branches you have, you can say$ git branchwhich used to be nothing more than a simple script around ls .git/refs/heads. There will be an asterisk in front of the branch youare currently on.Sometimes you may wish to create a new branch without actually checking it out and switching to it. If so, just use the command$ git branch <branchname> [startingpoint]which will simply create the branch, but will not do anything further. You can then later — once you decide that you want to actuallydevelop on that branch — switch to that branch with a regular git checkout with the branchname as the argument.MERGING TWO BRANCHESOne of the ideas of having a branch is that you do some (possibly experimental) work in it, and eventually merge it back to the mainbranch. So assuming you created the above mybranch that started out being the same as the original master branch, let’s make surewe’re in that branch, and do some work there.$ git checkout mybranch$ echo "Work, work, work" >>hello$ git commit -m "Some work." -i helloHere, we just added another line to hello, and we used a shorthand for doing both git update-index hello and git commit by justgiving the filename directly to git commit, with an -i flag (it tells Git to include that file in addition to what you have done tothe index file so far when making the commit). The -m flag is to give the commit log message from the command line.Now, to make it a bit more interesting, let’s assume that somebody else does some work in the original branch, and simulate that bygoing back to the master branch, and editing the same file differently there:$ git checkout masterHere, take a moment to look at the contents of hello, and notice how they don’t contain the work we just did in mybranch — becausethat work hasn’t happened in the master branch at all. Then do$ echo "Play, play, play" >>hello$ echo "Lots of fun" >>example$ git commit -m "Some fun." -i hello examplesince the master branch is obviously in a much better mood.Now, you’ve got two branches, and you decide that you want to merge the work done. Before we do that, let’s introduce a coolgraphical tool that helps you view what’s going on:$ gitk --allwill show you graphically both of your branches (that’s what the --all means: normally it will just show you your current HEAD) andtheir histories. You can also see exactly how they came to be from a common source.Anyway, let’s exit gitk (^Q or the File menu), and decide that we want to merge the work we did on the mybranch branch into themaster branch (which is currently our HEAD too). To do that, there’s a nice script called git merge, which wants to know whichbranches you want to resolve and what the merge is all about:$ git merge -m "Merge work in mybranch" mybranchwhere the first argument is going to be used as the commit message if the merge can be resolved automatically.Now, in this case we’ve intentionally created a situation where the merge will need to be fixed up by hand, though, so Git will do asmuch of it as it can automatically (which in this case is just merge the example file, which had no differences in the mybranchbranch), and say:Auto-merging helloCONFLICT (content): Merge conflict in helloAutomatic merge failed; fix conflicts and then commit the result.It tells you that it did an "Automatic merge", which failed due to conflicts in hello.Not to worry. It left the (trivial) conflict in hello in the same form you should already be well used to if you’ve ever used CVS, solet’s just open hello in our editor (whatever that may be), and fix it up somehow. I’d suggest just making it so that hello containsall four lines:Hello WorldIt's a new day for gitPlay, play, playWork, work, workand once you’re happy with your manual merge, just do a$ git commit -i hellowhich will very loudly warn you that you’re now committing a merge (which is correct, so never mind), and you can write a small mergemessage about your adventures in git merge-land.After you’re done, start up gitk --all to see graphically what the history looks like. Notice that mybranch still exists, and you canswitch to it, and continue to work with it if you want to. The mybranch branch will not contain the merge, but next time you merge itfrom the master branch, Git will know how you merged it, so you’ll not have to do that merge again.Another useful tool, especially if you do not always work in X-Window environment, is git show-branch.$ git show-branch --topo-order --more=1 master mybranch* [master] Merge work in mybranch! [mybranch] Some work.
gitcore-tutorial --stdin, ...
-
*+ [mybranch] Some work.* [master^] Some fun.The first two lines indicate that it is showing the two branches with the titles of their top-of-the-tree commits, you are currentlyon master branch (notice the asterisk * character), and the first column for the later output lines is used to show commits containedin the master branch, and the second column for the mybranch branch. Three commits are shown along with their titles. All of themhave non blank characters in the first column (* shows an ordinary commit on the current branch, - is a merge commit), which meansthey are now part of the master branch. Only the "Some work" commit has the plus + character in the second column, because mybranchhas not been merged to incorporate these commits from the master branch. The string inside brackets before the commit log message isa short name you can use to name the commit. In the above example, master and mybranch are branch heads. master^ is the first parentof master branch head. Please see gitrevisions(7) if you want to see more complex cases.NoteWithout the --more=1 option, git show-branch would not output the [master^] commit, as [mybranch] commit is a common ancestor ofboth master and mybranch tips. Please see git-show-branch(1) for details.NoteIf there were more commits on the master branch after the merge, the merge commit itself would not be shown by git show-branch bydefault. You would need to provide --sparse option to make the merge commit visible in this case.Now, let’s pretend you are the one who did all the work in mybranch, and the fruit of your hard work has finally been merged to themaster branch. Let’s go back to mybranch, and run git merge to get the "upstream changes" back to your branch.$ git checkout mybranch$ git merge -m "Merge upstream changes." masterThis outputs something like this (the actual commit object names would be different)Updating from ae3a2da... to a80b4aa....Fast-forward (no commit created; -m option ignored)example | 1 +hello | 1 +2 files changed, 2 insertions(+)Because your branch did not contain anything more than what had already been merged into the master branch, the merge operation didnot actually do a merge. Instead, it just updated the top of the tree of your branch to that of the master branch. This is oftencalled fast-forward merge.You can run gitk --all again to see how the commit ancestry looks like, or run show-branch, which tells you this.$ git show-branch master mybranch! [master] Merge work in mybranch* [mybranch] Merge work in mybranch
gitcore-tutorial - ...
--
MERGING EXTERNAL WORKIt’s usually much more common that you merge with somebody else than merging with your own branches, so it’s worth pointing out thatGit makes that very easy too, and in fact, it’s not that different from doing a git merge. In fact, a remote merge ends up beingnothing more than "fetch the work from a remote repository into a temporary tag" followed by a git merge.Fetching from a remote repository is done by, unsurprisingly, git fetch:$ git fetch <remote-repository>One of the following transports can be used to name the repository to download from:SSHremote.machine:/path/to/repo.git/ orssh://remote.machine/path/to/repo.git/This transport can be used for both uploading and downloading, and requires you to have a log-in privilege over ssh to the remotemachine. It finds out the set of objects the other side lacks by exchanging the head commits both ends have and transfers (closeto) minimum set of objects. It is by far the most efficient way to exchange Git objects between repositories.Local directory/path/to/repo.git/This transport is the same as SSH transport but uses sh to run both ends on the local machine instead of running other end on theremote machine via ssh.Git Nativegit://remote.machine/path/to/repo.git/This transport was designed for anonymous downloading. Like SSH transport, it finds out the set of objects the downstream sidelacks and transfers (close to) minimum set of objects.HTTP(S)http://remote.machine/path/to/repo.git/Downloader from http and https URL first obtains the topmost commit object name from the remote site by looking at the specifiedrefname under repo.git/refs/ directory, and then tries to obtain the commit object by downloading from repo.git/objects/xx/xxx...using the object name of that commit object. Then it reads the commit object to find out its parent commits and the associatetree object; it repeats this process until it gets all the necessary objects. Because of this behavior, they are sometimes alsocalled commit walkers.The commit walkers are sometimes also called dumb transports, because they do not require any Git aware smart server like GitNative transport does. Any stock HTTP server that does not even support directory index would suffice. But you must prepare yourrepository with git update-server-info to help dumb transport downloaders.Once you fetch from the remote repository, you merge that with your current branch.However — it’s such a common thing to fetch and then immediately merge, that it’s called git pull, and you can simply do$ git pull <remote-repository>and optionally give a branch-name for the remote end as a second argument.NoteYou could do without using any branches at all, by keeping as many local repositories as you would like to have branches, andmerging between them with git pull, just like you merge between branches. The advantage of this approach is that it lets you keepa set of files for each branch checked out and you may find it easier to switch back and forth if you juggle multiple lines ofdevelopment simultaneously. Of course, you will pay the price of more disk usage to hold multiple working trees, but disk spaceis cheap these days.It is likely that you will be pulling from the same remote repository from time to time. As a short hand, you can store the remoterepository URL in the local repository’s config file like this:$ git config remote.linus.url http://www.kernel.org/pub/scm/git/git.git/and use the "linus" keyword with git pull instead of the full URL.Examples.1. git pull linus2. git pull linus tag v0.99.1the above are equivalent to:1. git pull http://www.kernel.org/pub/scm/git/git.git/ HEAD2. git pull http://www.kernel.org/pub/scm/git/git.git/ tag v0.99.1HOW DOES THE MERGE WORK?We said this tutorial shows what plumbing does to help you cope with the porcelain that isn’t flushing, but we so far did not talkabout how the merge really works. If you are following this tutorial the first time, I’d suggest to skip to "Publishing your work"section and come back here later.OK, still with me? To give us an example to look at, let’s go back to the earlier repository with "hello" and "example" file, andbring ourselves back to the pre-merge state:$ git show-branch --more=2 master mybranch! [master] Merge work in mybranch* [mybranch] Merge work in mybranch
gitcore-tutorial -- ...