Git Ref Card
Git Ref Card
CONTENTS
ö ö Advanced Commands
Why Get Git? repository (or "repo" in common parlance) leads to setting up repos
Git is a postmodern version control system that offers the familiar everywhere. It feels frictionless.
capabilities of CVS or Subversion, but doesn't stop at just matching
From there, you'll progress to the second epiphany of being able to
existing tools. Git stretches the very notion of version control systems
share a repository and a changeset directly with a colleague without
(VCS) by its ability to offer almost all its features for use offline and
any complicated setup, without a check-in to a central server, without
without a central server. It is the brainchild of Linus Torvalds, the
direct network connectivity, and without having to worry about
creator of Linux, with the first prototype written in a vitriolic two-
firewalls getting in the way. Git has done technologically for version
week response to the "BitKeeper debacle" of 2005.
control what BitTorrent did for file sharing. It permanently replaced
Today, Git is effectively the de facto standard for software version the spoke and hub structure with a peer-to-peer model, and there's
control and is an expected tool in every developer's toolbox. no turning back. It supports transmitting binary sets of changes
Users reference its blistering performance, usage flexibility, via USB stick, email, or in the traditional style (over a network), but
offline capabilities, and collaboration features as their motivation amazingly, via HTTP, FTP, SCP, Samba, SSH, or WebDAV.
for switching.
Let's get started with Git. You'll be using it like a master in no time at all.
1
TAKE
CONTROL
of Your Open
Source Software
Getting Started change the directories to either a blank folder or an existing project
that you want to put under version control. Then initialize the
INSTALLING GIT
Git has a very light footprint for its installation. For most platforms, directory as a Git repository by typing the following commands:
you can simply copy the binaries to a folder that is on the executable $ git init
search $PATH . Git is primarily written in C, which means there is a $ git add .
unique distribution for each supported platform. $ git commit -m 'The first commit'
The canonical reference for Git installers can be found on a subpage The first command in the sequence, init, builds a .git directory that
of the official Git site. There are a number of installers available contains all the metadata and repository history. Unlike many other
there for those who don't want to go through the hassle of doing the version control systems, Git uniquely stores everything in just a
installation manually. In addition, also available at the official Git single directory at the top of the project — meaning no pollution in
download site are links to older distributions of the Git binary. every directory.
You can confirm that Git is installed and available with: Next, the add command with the dot wildcard tells Git to start tracking
changes for the current directory, its files, and for all folders beneath.
$ git --version
git version 2.19.1 Lastly, the commit function takes all the "staged" previous additions
and makes them permanent in the repository's history in a
ESTABLISHING USER CREDENTIALS transactional action. Rather than letting Git prompt the user via the
Once you have selected a suitable distribution of Git for your platform, default text editor, the -m option preemptively supplies the commit
you'll need to identify yourself with a username and email address to Git. message to be saved alongside the committed files. Omitting this flag
will use your system's default $EDITOR, falling back to vi as the default.
In a separation of concerns most satisfying to the purist, Git does
not directly support repository authentication or authorization. It It is amazing and exciting to be able to truthfully say that you
delegates this in a very functional way to the protocol (commonly SSH) can use the basics of Git for locally versioning files with just these
or operating system (file system permissions) hosting or serving up the three commands.
repository. Thus, the user information provided during your first Git
setup on a given machine is purely for "credit" of your code contributions. CLONING EXISTING PROJECTS
An equally common use case for Git is starting from someone
With the binaries on your $PATH , issue the following three commands else's repository history. This is similar to the checkout concept
just once per new machine on which you'll be using Git. Replace the in Subversion or other centralized version control systems. The
username and email address with your preferred credentials. difference in a DVCS is that the entire history, not just the latest
version, is retrieved and saved to the local user's disk.
$ git config --global user.name "matthew.
mccullough" The syntax to pull down a local copy of an existing repo is:
$ git config --global user.email "matthew@
ambientideas.com" # ssh protocol (requires SSH credentials to be
established):
$ git config --global color.ui "auto"
$ git clone [email protected]:mrasband/gitrefcard.git
If you are intrigued by all the potential nuances of a Git setup, here
The protocol difference often signifies access to the origin repository.
are several in-depth tutorials on setting up Git:
Typically, HTTPS is used for read-only access (or when SSH is not
• Installing Git on Mac, Windows, and Linux configured) and SSH will be used for read-write access; however, this
• Getting Started and Installing Git The clone command performs several subtasks under the hood. It
sets up a remote (a Git repository address bookmark) named origin
CREATING A REPOSITORY that points to the location [email protected]:mrasband/gitrefcard. git.
Now that Git is installed and the user information is established, you Next, clone asks this location for the contents of its entire repository.
can begin establishing new repositories. From a command prompt, Git copies those objects in a zlib-compressed manner over
the network to the requestor's local disk. Lastly, clone switches to a more prudent to just directly tell Git to relocate a file and track its
branch named master, which is equivalent to Subversion's trunk, as new destination.
the current working copy. The local copy of this repo is now ready to
$ git mv originalfile.txt subdir/newfilename.txt
have edits made, branches created, and commits issued — all while
online or offline.
If you wish to expunge a file from the current state of the branch,
TREEISH AND HASHES simply tell Git to remove it. It will be put in a pending deletion state
Rather than a sequential revision ID, Git marks each commit with a and can be confirmed and completed by the next commit.
SHA-1 hash that is unique to the person committing the changes, the
folders, and the files comprising the changeset. This allows commits $ git rm fileyouwishtodelete.txt
to be made independent of any central coordinating server.
VIEWING
A full SHA-1 hash is 40 hex characters:
Daily work calls for strong support of viewing current and historical
b0c2c709cf57f3fa6e92ab249427726b7a82d221.
facts about your repository, often from different, perhaps even
orthogonal points of view. Git satisfies those demands in spades.
To efficiently navigate the history of hashes, several symbolic
shorthand notations can be used as listed in the table below.
STATUS
Additionally, any unique sub-portion of the hash can be used. Git
To check the current status of a project's local directories and files
will let you know when the characters supplied are not enough to be
(modified, new, deleted, or untracked), invoke the status command:
unique. In most cases, four or five characters are sufficient.
$ git status
TREEISH DEFINITION
HEAD The current committed version DIFF
HEAD^1, HEAD~1 One commit ago A patch-style view of the difference between the currently edited and
HEAD^^, HEAD~2 Two commits ago committed files or any two points in the past can easily be summoned.
HEAD~N N Commits ago The .. operator signifies a range is being provided. An omitted
User definited tag was applied to the code when second element in the range implies a destination of the current
RELEASE-1/0
it was certified for release
committed state, also known as HEAD:
The Typical Local Workflow Git allows for diffing between the local files, the stage files, and the
committed files with a great deal of precision.
EDITING
Once you've cloned or initialized a new Git project, just start changing
COMMAND DEFINITION
files as needed for your current assignment. There is no pessimistic
locking of files by teammates. In fact, there's no locking at all. Git Everything unstaged (not git added) diffed to the
git diff
last commit
operates in a very optimistic manner, confident that its merge
capabilities are a match for any conflicted changes that you and your git diff- Everything staged (git added) diffed to the last
colleagues can craft. cached commit
If you need to move a file, Git can often detect your manual relocation Everything unstaged and staged diffed to the last
git diff HEAD
commit
of the file and will show it as a pending "move." However, it is often
LOG Specifying a folder name as the target of a git add recursively stages
The full list of changes since the beginning of time (or optionally, since files in any subdirectories.
a certain date) is right at your fingertips, even when disconnected
The -i option activates interactive add mode, in which Git prompts
from all networks:
for the files to be added or excluded from the next commit.
$ git log
$ git log --since=yesterday $ git add -i
$ git log --since=2weeks
The -p option is a shortcut for activation of the patch** sub-mode of
BLAME
the interactive prompt, allowing for precise pieces within a file to be
If trying to discover why and when a certain line was added, cut to the
selected for staging.
chase and have Git annotate each line of a source file with the name
and date it was last modified: $ git add -p
$ git checkout -- src/main/java/com.mrasband. Git requires that a message be present upon commit; leaving
platform/models/Person.java the message blank will abort the commit and leave the staged blobs
in place.
ADDING (STAGING)
The default editor can be changed with a Git configuration or by
When the developer is ready to put files into the next commit, they
setting the $EDITOR environment variable:
must be first staged with the add command. Users can navigate to
any directory, adding files item by item or by wildcard. $ git config --global core.editor <emacs|vim|subl
--wait|atom --wait>
$ git add <filename, directory name, or wildcard>
$ git add submodule1/Application.java To supply the commit message directly at the command prompt:
$ git add .
$ git add *.java $ git commit -m "<your commit message>"
To view the statistics and facts about the last commit: MERGING
Like other popular VCSes, Git allows you to merge one or more
$ git show
branches into the current branch.
If a mistake was made in the last commit's message, edit the commit
$ git merge <branch one>
text while leaving the changed files as-is with: $ git merge <branch one> <branch two>
$ git checkout <remote and local branch name> Git. You can push or pull, depending on your desired workflow with
colleagues and based on the repository operating system file and
protocol permissions. Git repositories are most typically shared via
LISTING BRANCHES
SSH, though a lightweight daemon is also provided.
To list the complete set of current local and remote branches known
to Git:
Git repository sharing via the simple daemon is introduced here. Sharing
$ git branch -a over SSH and Gitosis is documented in the Git Community Book.
The local branches typically have simple names like "master" and REMOTES
"experiment". Local branches are shown in white by Git's default While full paths to other repositories can be specified as a source or
syntax highlighting while the currently tracked branch is green with destination with most Git commands, this quickly becomes unwieldy
an asterisk prefix. Remote branches are prefixed by remotes and are and a shorthand solution is called for. In Git-speak, these bookmarks
shown in red. of other repository locations are called remotes.
A remote called origin is automatically created if you cloned a remote $ git bundle create catchupsusan.bundle HEAD~8..
repository. The full address of that remote can be viewed with: HEAD
$ git bundle create catchupsam.bundle
$ git remote -v --since=10days master
To add a new remote name: These diffs can be treated just like any other remote, even though
they are a local file on disk. The contents of the bundle can be
$ git remote add <remote name> <remote git
address> inspected with ls-remote and the contents pulled into the local
$ git remote add upstream [email protected]:mrasband/ repository with fetch. Many Git users add a file extension of .bundle as
gitrefcard.git a matter of convention.
destination of the merge. released along with Git. Some of them include significant advanced
functionality and are available on multiple platforms. Some of the
$ git pull
more widely used ones include Tower, SourceTree, GitEye, and GitHub
$ git pull <remote name>
Desktop. Unfortunately, GitHub Desktop currently only works with
$ git pull <remote name> <branch name>
GitHub and GitHub Enterprise repositories. However, given the wide
use of GitHub as an online repository, it's likely that you'll run into the
PULL
GitHub Desktop client at some point.
Pulling is the combination of a fetch and a merge as per the previous
section all in one seamless action.
IDES
$ git pull Java IDEs including IntelliJ, Eclipse (eGit), and NetBeans (NBGit) all offer
$ git pull <remote name> native or simple plugin support for Git through their traditional source
$ git pull <remote name> <branch name> code control integration points. However, there are a number of other
applications that also offer direct Git integration, as well. This includes
In the cases in which a merge commit may not be desired and the
applications such as Sublime Text, Atom, VS Code, Vim, and Emacs.
rebasing behavior is preferred, pull supports a rebase flag.
Numerous other platform-native GUIs offer graphically rich history
$ git pull --rebase <remote name> <branch name>
browsing, branch visualization, merging, staging, and commit features.
Devada, Inc.
600 Park Offices Drive
Suite 150
Research Triangle Park, NC
DZone communities deliver over 6 million pages each
month to more than 3.3 million software developers, 888.678.0399 919.678.0300
architects, and decision makers. DZone offers something for
Copyright © 2019 DZone, Inc. All rights reserved. No part of this publication
everyone, including news, tutorials, cheat sheets, research
may be reproduced, stored in a retrieval system, or transmitted, in any form
guides, feature articles, source code, and more. "DZone is a or by means electronic, mechanical, photocopying, or otherwise, without
developer’s dream," says PC Magazine. prior written permission of the publisher.