Git Cheat Sheet

By YuwebDesign

Command Description Example
git config ‐‐global user.name “username” sets the name you want attached to commit transactions $ git config ‐‐global user.name “John Doe”
git config ‐‐global user.email email@example.com sets the email you want attached to commit transactions $ git config ‐‐global user.email johndoe@example.com
git config ‐‐global user.name shows the name you set in config as attached to commit transactions John Doe
git config ‐‐global user.email shows the email you set in config as attached to commit transactions johndoe@example.com

Command Description Example
git gui& Open git GUI

Command Description Example
gitk& Open git gitk
(graphical history viewer)

Command Description Example
git log Lists version history for the current branch
lists each commit with its SHA-1 checksum,
the author’s name and email,
the date written,
and the commit message.

By default, with no arguments,
git log lists the commits
made in that repository
in reverse chronological order
(most recent commits first).

git log [option] [output limitations]

Limiting Log Output
-n - show the last n commits.
‐‐since, ‐‐after, ‐‐until, ‐‐before – time-limiting options
‐‐author – filters on a specific author
‐‐committer – filters on a specific committer
‐‐grep – searches for keywords in the commit messages
git log -S string – takes a string and shows only those commits that changed the number of occurrences of that string.
git log path/to/file-or-directory – limit the log output to commits that introduced a change to those files. This is always the last option and is generally preceded by double dashes (‐‐) to separate the paths from the options
‐‐no-merges – prevents the display of merge commits ( which typically aren’t very informative)

You can specify more than one instance
of both ‐‐author and ‐‐grep search criteria.

This will limit the commit output to commits
that match any of the ‐‐author patterns
and any of the ‐‐grep patterns.

However, adding the ‐‐all-match option
further limits the output to just those commits
that match all ‐‐grep patterns.

$ git log –since=2.weeks
(or”2008-01-15″ or “2 years 1 day 3 minutes ago”)

$ git log -S function_name
find the last commit that added or removed a reference to a specific function

$ git log –pretty=”%h – %s” –author=’Junio C Hamano’ –since=”2008-10-01″ \
–before=”2008-11-01″ –no-merges — t/

git log [option]

-p – Show the patch introduced with each commit.

‐‐stat – Show statistics for files modified in each commit.

‐‐shortstat – Display only the changed/insertions/deletions line from the –stat command.

‐‐name-only – Show the list of files modified after the commit information.

‐‐name-status – Show the list of files affected with added/modified/deleted information as well.

‐‐abbrev-commit – Show only the first few characters of the SHA-1 checksum instead of all 40.

‐‐relative-date – Display the date in a relative format (for example, “2 weeks ago”) instead of using the full date format.

‐‐graph – Display an ASCII graph of the branch and merge history beside the log output.

‐‐pretty – Show commits in an alternate format. Options include oneline, short, full, fuller, and format (where you specify your own format).

‐‐oneline – Shorthand for ‐‐pretty=oneline ‐‐abbrev-commit used together.

git log -p [-#ofentries-to-show]
git log ‐‐patch [-#ofentries-to-show]
shows the difference (the patch output) introduced in each commit.

You can limit the number of log entries displayed,
e.g., using -2 will show only the last two entries.

$ git log -p -2
git log ‐‐stat Shows abbreviated stats for each commit:

prints below each commit entry a list of modified files,
how many files were changed,
and how many lines in those files were added and removed.

It also puts a summary of the information at the end.

git log ‐‐pretty=option


  1. online,
  2. short,
  3. full,
  4. fuller
  5. format

git log ‐‐pretty=format

%H – Commit hash
%h – Abbreviated commit hash
%T – Tree hash
%t – Abbreviated tree hash
%P – Parent hashes
%p – Abbreviated parent hashes
%an – Author (originally wrote the work) name
%ae – Author email
%ad – Author date (format respects the ‐‐date=option)
%ar – Author date, relative
%cn – Committer (last applied the work) name
%ce – Committer email
%cd – Committer date
%cr – Committer date, relative
%s – Subject

Pretty changes the log output to formats other than the default.

  1. oneline – prints each commit on a single line, which is useful if you’re looking at a lot of commits.
  2. short, full, and fuller – show the output in roughly the same format but with less or more information, respectively
  3. format – allows you to specify your own log output format.
    This is especially useful when you’re generating output for machine parsing — because you specify the format explicitly, you know it won’t change with updates to Git
$ git log ‐‐pretty=oneline

$ git log ‐‐pretty=format:”%h – %an, %ar : %s”
ca82a6d – Scott Chacon, 6 years ago : changed the version number
085bb3b – Scott Chacon, 6 years ago : removed unnecessary test
a11bef0 – Scott Chacon, 6 years ago : first commit

git log ‐‐graph adds ASCII graph showing your branch and merge history

Particularly useful with oneline and format options

$ git log –pretty=format:”%h %s” –graph
git log ‐‐follow [file] Lists version history for a [file], including renames

Command Description Example
git status Checks the status of your files
list all new or modified files to be committed
tells which branch you’re on
informs if local branch (master) has diverged from the same branch on the server (origin)
git status -s
git status ‐‐short
short status flag
shows changes in a more compact way
git diff Compares what is in your working directory with what is in your staging area.
Shows changes made but not yet staged.
git diff ‐‐staged
= git diff ‐‐cached
compares your staged changes to your last commit
Shows what you have staged that will go into your next commit.

It’s important to note that git diff by itself doesn’t show all changes made since your last commit — only changes that are still unstaged. If you’ve staged all of your changes, git diff will give you no output.

git diff ‐‐name-only ‐‐cached Git list of staged files
git diff [branch1]…[branch2] Shows content differences between two branches

Command Description Example
git add [file-name] snapshots [file_name] in preparation for versioning
git add directory-name/\* snapshots directory-name/ in preparation for versioning git add conspects/\*
git add –A = git add ‐‐all add changes from all tracked and untracked files
git add [options] [‐‐] [pathspec]…

-n, ‐‐dry-run dry run
-v, ‐‐verbose be verbose

-i, ‐‐interactive interactive picking
-p, ‐‐patch select hunks interactively
-e, ‐‐edit edit current diff and apply
-f, ‐‐force allow adding otherwise ignored files
-u, ‐‐update update tracked files
‐‐renormalize renormalize EOL of tracked files (implies -u)
-N, ‐‐intent-to-add record only the fact that the path will be added later
-A, ‐‐all add changes from all tracked and untracked files
‐‐ignore-removal ignore paths removed in the working tree (same as ‐‐no-all)
‐‐refresh don’t add, only refresh the index
‐‐ignore-errors just skip files which cannot be added because of errors
‐‐ignore-missing check if – even missing – files are ignored in dry run
‐‐chmod (+|-)x override the executable bit of the listed files

Command Description Example
git commit record file snapshots permanently in file history
launches your editor of choice
remove comments and type your commit message, or you can leave them there to help you remember what you’re committing.
git commit -v record file snapshots permanently in file history
launches your editor of choice
puts the diff of your change in the editor
to see exactly what changes you’re committing.
git commit –m “descriptive message” record file snapshots permanently in file history
with the [descriptive message]
type your commit message inline with the commit command
esc:wq – if forgot [descriptive message]
git commit –a Skip the staging area
automatically stage every file that is already tracked
before doing the commit,
letting you skip the git add part
$ git commit -a -m ‘added new benchmarks’
git show [commit] Outputs metadata and content changes of the specified commit
git reset [file-name] unstages file but preserves its contents

Undoing changes in Git depends on the level of the change to be discarded:

Git Undoing Changes

Command Description Example
git checkout ‐‐ file-name Unmodifying a modified file (previously added to git)
discard changes in working directory

If you don’t want to keep the changes to the files,
you can revert it back to what it looked like when you last committed

Dangerous command – any local changes you made to that file are gone — Git just replaced that file with the most recently-committed version. Anything that is committed in Git can almost always be recovered.

If you would like to keep the changes made to file but still need to get it out of the way for now, Git Branching is better way to go.

$ git checkout ‐‐ CONTRIBUTING.md
git checkout . Unmodify everything within the directory (previously added to git)
git clean -xdf Clean working directory from all newly created files
(never added to git before)
git reset ‐‐ file.txt Undoes last commit for file.txt preserving changes locally
git reset HEAD file-name unstages a file from being committed in the upcoming commit $ git reset HEAD CONTRIBUTING.md
Unstages changes after reset to CONTRIBUTING.md file
git reset HEAD^^
git reset HEAD~2
unstages last two commits (in local branch, not yet pushed to remote)
Number of caret signs (^) or a number after a tilda (~)represents the number of commits
git reset HEAD^^
git reset HEAD~2
Remove the last two commits from the local branch
git reset ‐‐soft HEAD^
git reset HEAD~1
unstage one commit preserving changes locally
(in local branch, not yet pushed to remote)
(return to “indexed”/”staged” state)
git reset HEAD^^
git reset HEAD~2
Remove the last two commits from the local branch
git commit ‐‐amend (-m “New commit message”) run this command immediately after your previous commit

fixes up the most recent commit without new snapshot
use to edit the previous commit message without changing its snapshot

You end up with a single commit — the second commit replaces the results of the first.

Useful when you commit too early,
forget to add some files,
or you mess up your commit message.

redo that commit,
make the additional changes you forgot,
stage them,
and commit again using ‐‐amend

git commit -m ‘initial commit’
git add forgotten_file git commit ‐‐amend (-m “New commit message”)
git reset ‐‐soft Undo commit, preserving changes locally
(return to “indexed”/”staged” state)
git reset
same as git reset ‐‐mixed
Undoes all commits, preserving changes locally
(return to “not indexed”/”not staged” state)
git reset [commit] Undoes all commits afer [commit], preserving changes locally
git reset ‐‐hard Discards all history (without preserving changes locally)
Can not be undone.
git reset ‐‐hard [commit] Discards all history and changes back to the specified commit

Git reset can be a dangerous command,
especially if you provide the ‐‐hard flag

git revert [commit sha1] Revert changes in the remote repo

Commit can become unreachable, e.g. after git reset command (after resetting the state of the repo to the previous commit) repository will be in a state that contains a detached commit.

It may appear as though we have lost or deleted the commit, but Git is very strict about not deleting history.

We can confirm it is still available, but detached, by using git checkout sha1 to visit it directly.

Command Description Example
execute git prune but be sure to pass some options to it
git prune ‐‐dry-run ‐‐verbose This command will most likely return empty output. Empty output implies that the prune will not actually delete anything.

commit is most likely not fully detached. Somewhere Git is still maintaining a reference to it. This is a prime example of why git prune is not to be used stand-alone outside of git gc.

git prune -n ‐‐dry-run Don’t execute the prune. Just show an output of what it will do
git prune -v ‐‐verbose Display output of all objects and actions taken by the prune
git prune ‐‐progress Displays output that indicates the progress of the prune
git prune ‐‐expire &lang:time⟩ Displays output that indicates the progress of the prune
git reflog Most likely Git is storing a reference to our detached commit in the reflog. We can investigate by running git reflog.
You should see some output describing the sequence of actions we took to get here.

In addition to preserving history in the reflog, Git has internal expiration dates on when it will prune detached commits. Again, these are all implementation details that git gc handles and git prune should not be used standalone.

git reflog expire ‐‐expire=now ‐‐expire-unreachable=now ‐‐all clear the reflog
This command will force expire all entries to the reflog that are older than now. This is a brutal and dangerous command that you should never have to use as casual Git user.

Command Description Example
git rm [-f] [files or directories or file-glob patterns] Deletes the file from the working directory and stages the deletion

If you simply remove the file from your working directory, it shows up under the “Changes not staged for commit” (that is, unstaged) area of your git status output.

To remove a file from Git,
you have to remove it from your tracked files
(more accurately, remove it from your staging area)
and then commit.

Git rm removes the file from your working directory so you don’t see it as an untracked file the next time around.

The next time you commit, the file will be gone and no longer tracked. If you modified the file or had already added it to the staging area, you must force the removal with the -f option. This is a safety feature to prevent accidental removal of data that hasn’t yet been recorded in a snapshot and that can’t be recovered from Git.

$ git rm –cached README

$ git rm log/\*.log
removes all files that have the .log extension in the log/ directory.

$ git rm \*~
This command removes all files whose names end with a ~.

git rm ‐‐cached [file] Keep the file in your working tree (locally on your hard drive) but remove it from your staging area (do not have Git track it anymore)

Command Description Example
git mv file-original file-renamed Renames the file and prepares it for commit $ mv README.md README

Renaming with mv is equivalent of using rm and add:
$ git rm README.md
$ git add README

Command Description Example
$ git help [verb]
$ man git-[verb]
get the comprehensive manual page (manpage) help
for any of the Git commands
git [verb] -h
git [verb] ‐‐help
more concise “help” output for a quick refresher
on the available options for a Git command
instead of the full-blown manpage help
$ git add -h

gitignore Syntax

Command Description Example
.gitignore [pattern]

Rules for patterns you can put in the .gitignore:

  1. Blank lines or lines starting with # are ignored.
  2. Standard glob patterns work, and will be applied recursively throughout the entire working tree.
  3. You can start patterns with a forward slash (/) to avoid recursivity.
  4. You can end patterns with a forward slash (/) to specify a directory.
  5. You can negate a pattern by starting it with an exclamation point (!).

Glob patterns are like simplified regular expressions that shells use:

  1. An asterisk (*) matches zero or more characters;
  2. [abc] matches any character inside the brackets (in this case a, b, or c);
  3. a question mark (?) matches a single character;
  4. brackets enclosing characters separated by a hyphen ([0-9]) matches any character between them (in this case 0 through 9).
  5. You can also use two asterisks to match nested directories; a/**/z would match a/z, a/b/z, a/b/c/z, and so on.
  1. Marks files that you don’t want Git to automatically add or even show you as being untracked.
  2. Creates a file listing patterns to match them named .gitignore
  3. These are generally automatically generated files such as log files or files produced by your build system.
  4. You may also include a log, tmp, or pid directory; automatically generated documentation; and so on.

Read more on .gitignore >>>

$ cat .gitignore
ignore any files ending in “.o” or “.a” — object and archive files that may be the product of building your code.
ignore all files whose names end with a tilde (~), which is used by many text editors such as Emacs to mark temporary files.

# ignore all .a files

# but do track lib.a, even though you’re ignoring .a files above

# only ignore the TODO file in the current directory, not subdir/TODO

# ignore all files in any directory named build

# ignore doc/notes.txt, but not doc/server/arch.txt

# ignore all .pdf files in the doc/ directory and any of its subdirectories

Git Branching: Group Changes in Local Branches

Command Description Example
git branch Lists all local branches in the current repository
git branch -v Lists all local branches in the current repository

Shows last commit on each branch

git branch -vv Lists all local branches in the current repository

Shows what each branch is tracking
and if your local branch is ahead, behind or both.

only since the last time you fetched from each server.
This command does not reach out to the servers,
it’s telling you about what it has cached from these servers locally.

git fetch ‐‐all; git branch -vv If you want totally up to date ahead and behind numbers, you’ll need to fetch from all your remotes right before running git branch -vv
git branch ‐‐merged
git branch ‐‐no-merged
Lists all local branches in the current repository

Filter this list to branches that you have or have not yet merged into the branch you’re currently on

For merged, branches on this list without the * in front of them are generally fine to delete with git branch -d; you’ve already incorporated their work into another branch, so you’re not going to lose anything.

git branch ‐‐no-merged master

Command Description Example
git branch branch-name Creates a new branch
without switching to that branch.

(now there are two branches:
master and branch-name,
with HEAD is still pointing to Master)

(creates a new pointer to the same commit you’re currently on)

Git knows what branch you’re currently on
by keeping a special pointer called HEAD
(points to the local branch you’re currently on).

Command Description Example
git branch -u remote/branch

git branch ‐‐set-upstream-to

Set a local branch to a remote branch you just pulled down,
or change the upstream branch you’re tracking
$ git branch -u origin/serverfix
Branch serverfix set up to track remote branch serverfix from origin.
git checkout branch-name switch to an existing branch
(moves HEAD [from master] to point to the branch-name).

Changes in new branch
will diverge from master branch of the project
so you can go in a different direction.

Changes are isolated in separate branches: you can switch back and forth between the branches and merge them together when you’re ready.

Switching branches changes files in your working directory.
If you switch to an older branch,
your working directory will be reverted
to look like it did the last time
you committed on that branch.

If your working directory or staging area
has uncommitted changes
that conflict with the branch you’re checking out,
Git won’t let you switch branches.
It’s best to have a clean working state
when you switch branches.
There are ways to get around this
(namely, stashing and commit amending).

git checkout testing
switch to branch named testing

git checkout master
switch to master branch
moves the HEAD pointer back to point to the master branch, puts files in working directory to snapshot that master points to.

git checkout ‐‐track remote/branch
= git checkout branch
set up tracking branches if you wish 
— ones that track branches on other remotes,
or don’t track the master branch.
$ git checkout ‐‐track origin/serverfix
Branch serverfix set up to track remote branch serverfix from origin.
Switched to a new branch ‘serverfix’

Same as

$ git checkout serverfix
Branch serverfix set up to track remote branch serverfix from origin.
Switched to a new branch ‘serverfix’

git checkout -b new-branch-name Creates a new branch
and switch to that new branch at the same time 
$ git checkout -b iss53
This is shorthand for:
$ git branch iss53
$ git checkout iss53
git checkout -b branch remote/branch

git checkout -b branch-name2 remote/branch-name1
sets up a local branch
with a different name than the remote branch

Creates a new branch
based off your remote-tracking branch
and switch to that new branch at the same time.

Checking out a local branch from a remote-tracking branch automatically creates what is called a “tracking branch” (and the branch it tracks is called an “upstream branch”).

Tracking branches are local branches that have a direct relationship to a remote branch.

If you’re on a tracking branch and type git pull, Git automatically knows which server to fetch from and which branch to merge in.

$ git checkout -b serverfix origin/serverfix

Create your own serverfix branch that you can work on, based off your remote-tracking branch
This gives you a local branch that you can work on that starts where origin/serverfix is

$ git checkout -b sf origin/serverfix
Branch sf set up to track remote branch serverfix from origin.
Switched to a new branch ‘sf’
Now, your local branch sf will automatically pull from origin/serverfix.

Command Description Example
git merge branch-name Combines branch-name’s history into the current branch

Recursive merge: Git performs a three-way merge
between the two latest branch snapshots
and the most recent common ancestor of the two,
creating a new snapshot (and commit).

Fast-forward merge: when merging one commit with a commit that can be reached by following the first commit’s history, Git simplifies things by moving the pointer forward because there is no divergent work to merge together.

Because we’re recording the parents when we commit,
finding a proper merge base for merging
is automatically done for us
and is generally very easy to do.
This encourages developers to use branches often.

$ git checkout master
Switched to branch ‘master’
$ git merge iss53

git merge master

git merge hotfix

$ git rebase base-branch-name Takes all the changes
that were committed on one branch
and replay them on a different branch.

Now you will be able to do a fast-forward merge.

Never rebase commits that exist outside your repository and people may have based work on them.

Rebasing makes for a cleaner history.
If you examine the log of a rebased branch, it looks like a linear history: it appears that all the work happened in series, even when it originally happened in parallel.

This operation works by going to the common ancestor of the two branches (the one you’re on and the one you’re rebasing onto), getting the diff introduced by each commit of the branch you’re on, saving those diffs to temporary files, resetting the current branch to the same commit as the branch you are rebasing onto, and finally applying each change in turn.

$ git checkout experiment
$ git rebase master
check out the experiment branch,
and then rebase it onto the master branch

At this point, you can go back to the master branch and do a fast-forward merge.
$ git checkout master
$ git merge experiment

$ git rebase –onto branch1 branch2 branch3

Now you can fast-forward branch1

$ git rebase –onto master server client

Take the client branch,
figure out the patches
since it diverged from the server branch,
and replay these patches in the client branch
as if it was based directly off the master branch instead.

Now you can fast-forward your master branch
$ git checkout master
$ git merge client

git cherry-pick commitSha enables arbitrary Git commits to be picked by reference and appended to the current working HEAD.

Cherry picking is the act of picking a commit from a branch and applying it to another.

Can cause duplicate commits and many scenarios where cherry picking would work, traditional merges are preferred instead.

Cherry-pick can be useful for:

  1. undoing changes:
    E.g., commit accidently made to the wrong branch.
    Switch to the correct branch and cherry-pick the commit to where it should belong.
  2. team collaboration:
    E.g., backend developer creates a data structure that the frontend will also need to utilize.
    The frontend developer could use git cherry-pick to continue progress on their side of the project.
  3. Bug hotfixes:
    E.g., patch commit cherry-picked directly to the master branch to fix the bug.
  4. Undoing changes and restoring lost commits:
    E.g., a feature branch may go stale and not get merged into master.
    Sometimes a pull request might get closed without merging.
    Git never loses those commits and through commands like git log and git reflog they can be found and cherry picked back to life.
git checkout master
git cherry-pick f

Command Description Example
git branch -d branch-name Deletes the specified branch $ git branch -d hotfix
git branch -D branch-name Force-deletes the specified branch $ git branch -D hotfix

Git Branching – Remote Branches (Remote Repositories)

Command Description Example
git remote lists the shortnames of each remote handle you’ve specified
git remote show origin Shows remote origin info

Lists URL for remote repository and tracking branch information.

Lists all the remote references it has pulled down.

$ git remote show origin
git ls-remote remote-name get a full list of remote references explicitly.

Remote references are references (pointers) in your remote repositories, including branches, tags, and so on.

git remote -v List your existing remotes in order to get the name of the remote you want to change

If you have more than one remote, the command lists them all.

Command Description Example
git clone implicitly adds the origin remote for you.

When you clone a repository, it generally automatically creates a master branch that tracks origin/master.

git remote set-url shortname url add a new remote Git repository explicitly
as a shortname you can reference easily
git remote set-url origin https://github.com/paulboone/ticgit
git remote set-url upstream https://github.com/USERNAME/REPOSITORY.git
git remote set-url myremote git@github.com:USERNAME/REPOSITORY.git
git remote add shortname url add a new remote Git repository explicitly
as a shortname you can reference easily
$ git remote add pb https://github.com/paulboone/ticgit

Command Description Example
git fetch remote fetches from remote repository
all the information remote has
but that you don’t yet have in your repository

downloads the data to your local repository
without modifying your working directory at all
doesn’t automatically merge data with any of your work
lets you merge it yourself.

when you do a fetch that brings down new remote-tracking branches, you don’t automatically have local, editable copies of them. You have only an origin/branch pointer that you can’t modify.

This command looks up which server “origin” is, fetches any data from it that you don’t yet have, and updates your local database, moving your origin/master pointer to its new, more up-to-date position.

You have to merge this work manually into your current working branch by git merge origin/branch.

git fetch origin
fetches any new work that has been pushed to server since you cloned (or last fetched from) it.

$ git fetch pb
Paul’s master branch is now accessible locally as pb/master — you can merge it into one of your branches, or you can check out a local branch at that point if you want to inspect it.

git pull Downloads bookmark history from the server you originally cloned from
and merges it into the code you’re currently working on.

It is essentially a git fetch immediately followed by a git merge in most cases.

If you have a tracking branch set up
either by explicitly setting it
or by having it created for you
by the clone or checkout commands

git pull will look up
what server and branch your current branch is tracking,
fetch from that server
and then try to merge in that remote branch.

Git clone automatically sets up your local master branch to track the remote master branch (or whatever the default branch is called) on the server you cloned from.

Generally it’s better to simply use the fetch and merge commands explicitly as the magic of git pull can often be confusing.

git push remote branch

git push remote branch-name1:branch-name2
push a local branch into a remote branch that is named differently

Uploads all local/master branch commits to remote/origin server

works only if you cloned from a server to which you have write access and if nobody has pushed in the meantime.

If you and someone else clone at the same time and they push upstream and then you push upstream, your push will rightly be rejected.

You’ll have to fetch their work first and incorporate it into yours before you’ll be allowed to push.

$ git push origin serverfix
push up branch named serverfix that you want to work on with others

git push origin serverfix:awesomebranch
pushes your local serverfix branch to the awesomebranch branch on the remote project

Command Description Example
git remote rename old-name new-name Changes a remote’s shortname
(including remote-tracking branch names)
$ git remote rename pb paul
renames pb to paul
remote-tracking branch names that used to be referenced at pb/master is now at paul/master
git remote remove branch-name

git remote rm branch-name

Removes a remote
all remote-tracking branches and configuration settings associated with that remote are also deleted.
$ git remote remove paul
git push origin ‐‐delete branch-name Deletes a remote branch

Basically all this does is remove the pointer from the server.

The Git server will generally keep the data there for a while
until a garbage collection runs,
so if it was accidentally deleted,
it’s often easy to recover.

$ git push origin ‐‐delete serverfix

Git on the Server

SSH (Secure Shell) Keys are an access credential that is used in the SSH protocol.

On Windows, SSH key pair can be generated by cmd, or SSH client like PuTTY, on Mac and Linux by terminal window.

SSH Key Pairs

SSH keys always come in pairs, every pair made up of a private key and a public key.

Kinds of SSH Keys
  1. User Keys
    If the private key and the public key remain with the user, this set of SSH keys is referred to as user keys.

    Private key: In a user key set, the private key remains on the system being used to access the remote system and is used to decrypt information that is exchanged in the SSH protocol.

    Private keys should never be shared with anyone.

    Public Key: A public key is used to encrypt information, can be shared, and is used by the user and the remote server.

    On the server end, the public key is saved in a file that contains a list of authorized public keys.

    On the user’s side, the public SSH key is stored in an SSH key management software or in a file on their computer.

  2. Host Keys
    If the private and public key are on a remote system, then this key pair is referred to as host keys.
  3. Session Keys
    Another type of SSH key is a session key. When a large amount of data is being transmitted, session keys are used to encrypt this information.

Run the following ls command to see if existing SSH keys are present:

ls -al ~/.ssh/id_*.pub
  1. If there are existing keys, you can either use those and skip the next step or backup up the old keys and generate a new one.
  2. If you see “No such file or directory” or “no matches found it means that you do not have an SSH key and you can proceed with the next step and generate a new one.

Setup SSH Passwordless Login

To set up a passwordless SSH login in Linux all you need to do is to

  1. generate a public authentication key
  2. and append it to the remote hosts ~/.ssh/authorized_keys file.
Step 1: Create SSH keys
Create the key pair on the client machine (there is a good chance that this will just be your computer)
ssh-keygen -t rsa
#Creates a new ssh key pair

ssh-keygen -t rsa -C “your_email@example.com”
#Creates a new ssh key, using the provided email as a label

ssh-keygen -t rsa -b 4096 -C “your_email@domain.com”
#generates a new 4096 bits SSH key pair with your email address as a comment

Step 2: Store SSH Keys locally
Store the Keys Locally
  1. Once you have entered the Gen Key command, you will get a few more questions:
    Enter file in which to save the key (/home/demo/.ssh/id_rsa)
  2. Press enter, saving the file to the user home (here user is called demo).
  3. If you use a non default file name, you have to tell ssh to use this keyfile.
    For example by adding to your .ssh/config
    IdentityFile ~/.ssh/yourcustomfilename

    Or by using
    ssh -i ~/.ssh/yourcustomfilename

Step 3: Store the Passphrase
Store the Passphrase or use no passphrase
Then you will be asked for a passphrase:
Enter passphrase (empty for no passphrase)

It’s up to you whether you want to use a passphrase.

  1. Entering a passphrase does have its benefits:
    the security of a key, no matter how encrypted,
    still depends on the fact that it is not visible to anyone else.

    Should a passphrase-protected private key fall into an unauthorized users possession,
    they will be unable to log in to its associated accounts until they figure out the passphrase,
    buying the hacked user some extra time.

  2. The only downside, of course, to having a passphrase,
    is then having to type it in each time you use the key pair.

Step 4: Store public key on the server
Store contents of public key id_rsa.pub in ~/.ssh/authorized_keys file on the remote machine
The easiest way to copy your public key to the server is to use a utility called ssh-copy-id:

ssh-copy-id remote_username@server_ip_address
  1. You should never save the file with its contents starting with —–BEGIN RSA PRIVATE KEY—– on the server, that is your private key.
  2. Instead, you must put the public key into the ~/.ssh/authorized_keys file.
    This public key has the .pub extension when generated using ssh-keygen and its contents begin with ssh-rsa AAAAB3.
  3. The permissions of ~/.ssh on the server should be 700.
    The file ~/.ssh/authorized_keys (on the server) is supposed to have a mode of 600.
    The permissions of the (private) key on the client-side should be 600.
Way 1: Step by Step

  1. ls -al ~/.ssh
    see if there is .ssh directory and list files within it
  2. mkdir -p ~/.ssh && chmod 700 ~/.ssh
    if no such directory exists, create it and give a permission 700
  3. touch ~/.ssh/authorized_keys && chmod 0644 ~/.ssh/authorized_keys
    create authorized_keys file and give it a permission 0644
  4. nano ~/.ssh/authorized_keys
    vi ~/.ssh/authorized_keys
    open authorized_keys file in the editor and copy-paste the contents of the public key file
Way 2: Single command
cat ~/.ssh/id_rsa.pub | ssh USER@HOST “mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys”
cat ~/.ssh/id_rsa.pub | ssh USER@HOST “umask 077 && mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys”

Some advantages:

  1. does not require ssh-copy-id to be installed.
  2. guarantees that mkdir works before attempting to append id_rsa.pub to authorized_keys.

If something went wrong, You can generate the public key from the private key at any time.

ssh-keygen -y -f key.pem > key.pub

Change the passphrase on your default DSA key

To change the passphrase on your default DSA key:

$ ssh-keygen -p -f ~/.ssh/id_dsa

then provide your old and new passphrase (twice) at the prompts.

Change the passphrase on your default RSA key

To change the passphrase on your default RSA key:

$ ssh-keygen -p -f ~/.ssh/id_rsa

then provide your old and new passphrase (twice) at the prompts.

Command Description Example
SSH Connection to a remote server
ssh user@ip [-p ####]

ssh user@domain [-p####]

connect to a remote server via SSH
using the remote user name, hostname and port (optional if default 22000).
ssh john@dev.example.com -p 2322

connect as a user named john to a host called dev.example.com on port 2322

Host hostname
HostName ip/domain
User username
Port ####
Simplify ssh connection by setting up config file (~/.ssh/config).

Now if you type in command line ssh hostname

ssh client will read the configuration file
and use the connection details
specified for the “hostname” host

E.g, if config is set up:
Host dev
HostName dev.example.com
User john
Port 2322

if you type in command line
ssh dev

the ssh client will read the configuration file
and use the connection details
specified for the “dev” host

$ alias hostname=’ssh user@domain/ip -p #####’

To connect type in command line:
$ hostname

create a simple alias in your shell to connect with hostname $ alias dev=’ssh fooey@dev.example.com -p 22000′

To connect type in command line:
$ dev

  1. OpenSSH client-side configuration file is named config.
  2. Config is stored in .ssh directory under user’s home directory.
  3. The ~/.ssh directory is automatically created when the user runs the ssh command for the first time.

Command Description Example
Create SSH Config File
mkdir -p ~/.ssh && chmod 700 ~/.ssh Create .ssh directory
If you have never used the ssh command first you’ll need to create the directory
ls -al ~/.ssh List files in .ssh directory
Lists the files in your .ssh directory, if they exist
touch ~/.ssh/config && chmod 600 ~/.ssh/config Create ~/.ssh/config file
By default the SSH configuration file may not exist so you may need to create it using the touch command.
Config file must be readable and writable only by the user, and not accessible by others

Command Description Example
SSH Config File Structure and Patterns
  1. The contents of the SSH client config file is organized into stanzas (sections).
  2. Each stanza starts with the Host directive and contains specific SSH options that are used when establish connection with the remote SSH server.
  3. Indentation is not required, but is recommended since it will make the file easier to read.
  4. The Host directive can contain one pattern or a whitespace-separated list of patterns.
  5. Each pattern can contain zero or more non-whitespace character or one of the following pattern specifiers:
    1. * – matches zero or more characters.
      E.g., Host * will match all host, while 192.168.0.* will match all hosts in the subnet.
    2. ? – matches exactly one character.
      E.g., Host 10.10.0.? will match all hosts in 10.10.0.[0-9] range.
    3. ! – at the start of a pattern will negate its match
      E.g.< Host 10.10.0.* ! will match any host in the subnet except
  6. The SSH client reads the configuration file stanza by stanza
    and if more than one patterns match,
    the options from the first matching stanza takes precedence.

    Therefore more host-specific declarations should be given at the beginning of the file,
    and more general overrides at the end of the file.

Host hostname1

Host hostname2

Host *

Shared SSH Config File Example:
Host targaryen
User daenerys
Port 7654
IdentityFile ~/.ssh/targaryen.key

Host tyrell

Host martell

Host *ell
user oberyn

Host * !martell
LogLevel INFO

Host *
User root
Compression yes

When running ssh tyrell the matching host patterns are:
Host tyrell, Host *ell, Host * !martell and Host *.

The options used in this case are:
User oberyn
LogLevel INFO
Compression yes

man ssh_config full list of available ssh options
Also available here

Command Description Example
Override SSH Config File Option
ssh -o “what-to-overwrite” hostname

The -F (configfile) switch allows you to specify an alternative per-user configuration file.

The ssh client receives its configuration in the following precedence order:
Options specified from the command line
Options defined in the ~/.ssh/config
Options defined in the /etc/ssh/ssh_config

If you want to override a single option you can specify it on the command line.

If you want your ssh client to ignore all of the options specified in your ssh configuration file, you can use:
ssh -F /dev/null user@example.com

If you want to override a single option you can specify it on the command line. For example if you have the following definition:

Host dev
HostName dev.example.com
User john
Port 2322
and you want to use all other options but to connect as user root instead of john simply specify the user on the command line:

ssh -o “User=root” dev

git remote set-url origin https://github.com/USERNAME/OTHERREPOSITORY.git Change your remote’s URL from SSH to HTTPS

git remote set-url origin git@github.com:USERNAME/OTHERREPOSITORY.git Change your remote’s URL from HTTPS to SSH

  1. Create additional ssh public keys

    Mine are:

  2. Add the newly generated ssh key to your additional GitHub account
  3. Open your ssh config file
    cd .ssh/config
  4. Modify the ssh config
    Host github.com-incodinggirls
      HostName github.com
      User git
      IdentityFile /Users/yulia/.ssh/id_rsa_girl
      IdentitiesOnly yes
    Host github.com
      HostName github.com
      User git
      IdentityFile /Users/yulia/.ssh/id_rsa
      IdentitiesOnly yes
  5. Now your will have to modify your github urls according to Host in your config file naming.
    origin	git@github.com:yuwebdesign/SeleniumHQ_POM_TestNG.git (fetch)
    origin	git@github.com-incodinggirls:in-coding-girls/SeleniumHQ_TestNg_POM_Framework.git (push)
    origin	git@github.com:yuwebdesign/SeleniumHQ_POM_TestNG.git (push)

    E.g. instead of


    I will have the following url


    because of the Host github.com-incodinggirls record in my ssh/config file

Read more >>>


Command Description Example
git init project-name creates new local repository with the specified name
git clone -o directory-name downloads a project and its entire version history with a different name instead of “origin”

“origin” is not special
Just like the branch name “master” does not have any special meaning in Git, neither does “origin”.

While “master” is the default name for a starting branch when you run git init which is the only reason it’s widely used, “origin” is the default name for a remote when you run git clone.

$ git clone -o booyah
clone with booyah/master as your default remote branch.
git clone url [directory-name] downloads a project and its entire version history $ git clone https://github.com/libgit2/libgit2
clones the Git linkable library called libgit2

$ git clone https://github.com/libgit2/libgit2 mylibgit
clones repository into a directory named mylibgit

  1. Create a new repository on GitHub.

    To avoid errors, do not initialize the new repository with README, license, or gitignore files.
    You can add these files after your project has been pushed to GitHub.

  2. Create a new repository on the command line:
    change the current working directory to where your local project will be and create a directory.

    cd myproject/path/directoryname
  3. create README.md
    echo README.md
  4. Initialize the local directory as a Git repository.
    git init
  5. Stage README.md in your new local repository for the first commit.
    git add README.md
  6. Commit the files that you’ve staged in your local repository.
    git commit -m "First commit"
    # Commits the tracked changes and prepares them to be pushed to a remote repository. 
  7. At the top of your GitHub repository’s Quick Setup page, click to copy the remote repository URL.
  8. In the Command prompt, add the URL for the remote repository where your local repository will be pushed (from step above).
    git remote add origin remoteRepositoryURL
    # Sets the new remote
  9. Verify the new remote URL
    git remote -v
    # Verifies the new remote URL
  10. Push the changes in your local repository to GitHub.
    git push -u origin master
    # Pushes the changes in your local repository up to the remote repository you specified

If a project has to have multiple git repos
(e.g. Bitbucket and Github)
it’s better that they remain in sync.

Instead of pushing each branch to each repo in turn,
Git allows pushing to multiple remotes using a single git push
through adding multiple pushurls for a given remote.

if you want to push to two or more repositories using a single command,
you can simply add additional pushurls for your origin remote,
you may create a new remote named all
if that makes logically more sense to you.

If you want to set additional pushurl for your origin remote:

  • Check your remote:
    git remote -v
    # Outputs the remote URLs


    git remote show origin
  • Add a pushurl to the origin remote, pointing to another repository


    git remote set-url --add --push remote_name url 


    git remote set-url --add --push origin git@github.com-incodinggirls:in-coding-girls/SeleniumHQ_TestNg_POM_Framework.git

    Running the command above
    adds a section to your repository’s .git/config file,
    specifying the name of the remote (origin),
    the URL of the remote repository,
    and the refspec to be used for fetching.

    It will change the remote.origin.pushurl config entry.
    Now pushes will be sent
    to both of these destinations,
    rather than the fetch URL.

  • Check your remotes:
    git remote -v
    # Outputs the remote URLs
    origin	git@github.com:yuwebdesign/SeleniumHQ_POM_TestNG.git (fetch)
    origin	git@github.com-incodinggirls:in-coding-girls/SeleniumHQ_TestNg_POM_Framework.git (push)
    origin	git@github.com:yuwebdesign/SeleniumHQ_POM_TestNG.git (push)
  • Read more here >>>, and here >>>

    1. Create a new repository on GitHub.

      To avoid errors, do not initialize the new repository with README, license, or gitignore files.
      You can add these files after your project has been pushed to GitHub.

    2. In command line change the current working directory to your local project.
      cd myproject/path/directoryname
    3. If does not exist yet, create README.md
      echo README.md
    4. If not yet done, initialize the local directory as a Git repository.
      git init
    5. If not yet done, stage files in your new local repository for the first commit.
      git add .
      # Adds the files in the local repository and stages them for commit. 
      #To unstage a file, use 'git reset HEAD YOUR-FILE'
    6. If not yet done, commit the files that you’ve staged in your local repository.
      git commit -m "First commit"
      # Commits the tracked changes and prepares them to be pushed to a remote repository. 
      # To remove this commit and modify the file, use 'git reset --soft HEAD~1' and commit and add the file again.
    7. At the top of your GitHub repository’s Quick Setup page, click to copy the remote repository URL.
    8. In the Command prompt, add the URL for the remote repository where your local repository will be pushed (from step above).
      git remote add origin remoteRepositoryURL
      # Sets the new remote
    9. Verify the new remote URL
      git remote -v
      # Verifies the new remote URL
    10. Push the changes in your local repository to GitHub.
      git push -u origin master
      # Pushes the changes in your local repository up to the remote repository you specified

    Read more >>>

    The GitHub Flow

    1. Clone our fork of the project locally
    2. Create a descriptive topic branch from master.
    3. Make some commits to improve the project.
    4. Push this branch to your GitHub project topic branch.
    5. Open a Pull Request on GitHub.
    6. Discuss, and optionally continue committing.
    7. The project owner merges or closes the Pull Request.
    8. Sync the updated master back to your fork.

    This is the basic workflow that most GitHub projects use.

    This is basically the Integration Manager workflow,
    but instead of using email to communicate and review changes, teams use GitHub’s web based tools.

    Command Description Example
    Contributing to a Project: Forking Projects
    People can fork a project,
    push to it,
    and contribute their changes back to the original repository by creating what’s called a Pull Request
    This opens up a discussion thread with code review, and the owner and the contributor can then communicate about the change until the owner is happy with it, at which point the owner can merge it in.
    contribute to an existing project
    to which you don’t have push access

    This way, projects don’t have to worry about adding users as collaborators to give them push access.

    GitHub will make a copy of the project
    that is entirely yours;

    a “fork” is simply the same project in your own namespace,
    allowing you to make changes to a project publicly
    as a way to contribute in a more open manner.

    $ git clone https://github.com/tonychacon/blink
    #Clone fork of the project locally

    $ cd blink
    $ git checkout -b slow-blink
    #Create a descriptive topic branch

    $ sed -i '' 's/1000/3000/' blink.ino (macOS)
    #Make our change to the code

    $ git diff --word-diff
    #Check that the change is good

    $ git commit -a -m 'three seconds is better'
    #Commit our change to the topic branch

    $ git push origin slow-blink
    #Push our new topic branch back up to our GitHub fork

    1. Once you’ve forked a GitHub repository, your repository (your "fork") exists independently from the original.
    2. In particular, when the original repository has new commits, GitHub informs you by a message like:
      This branch is 5 commits behind progit:master.
    3. But your GitHub repository will never be automatically updated by GitHub; this is something that you must do yourself.
    Command Description Example
    Keeping your GitHub public repository up-to-date
    Update with no configuration With no configuration:

    1. If you were on another branch, return to master.
    2. Fetch changes from fetch URL and merge them into master.
    3. Push your master branch to origin.
    No configuration:
    $ git checkout master
    #If you were on another branch, return to master.
    $ git pull https://github.com/progit/progit2.git
    #Fetch changes from https://github.com/progit/progit2.git and merge them into master.
    $ git push origin master
    #Push your master branch to origin.
    Automate fetch URL configuration Automate fetch URL configuration:

    1. Add the source repository and give it a name.
    2. Set your master branch to fetch from the remote.
    3. Define the default push repository to origin.
    4. $ git checkout master
      $ git pull
      $ git push
    $ git remote add progit https://github.com/progit/progit2.git
    #Add the source repository and give it a name progit
    $ git branch --set-upstream-to=progit/master master
    #Set your master branch to fetch from the progit remote.
    $ git config --local remote.pushDefault origin
    #Define the default push repository to origin

    Once this is done, the workflow becomes much simpler:
    $ git checkout master
    #If you were on another branch, return to master.
    $ git pull
    #Fetch changes from progit and merge changes into master.
    $ git push
    #Push your master branch to origin.

    Many projects don’t really think of Pull Requests
    as queues of perfect patches
    that should apply cleanly in order,
    as most mailing list-based projects
    think of patch series contributions.

    Most GitHub projects think about Pull Request branches
    as iterative conversations around a proposed change,
    culminating in a unified diff that is applied by merging.

    Pushing the “Merge” button on the site purposefully creates a merge commit that references the Pull Request so that it’s easy to go back and research the original conversation if necessary.

    Command Description Example
    Advanced Pull Requests: Keeping up with Upstream
    GitHub will test and let you know at the bottom of every Pull Request if the merge is trivial or not.

    If you see something like "Pull Request does not merge cleanly", you’ll want to fix your branch so that it turns green and the maintainer doesn’t have to do extra work.

    You can either rebase your branch on top of whatever the target branch is (normally the master branch of the repository you forked), or you can merge the target branch into your branch.

    Most developers on GitHub will choose to do the latter. What matters is the history and the final merge, so rebasing isn’t getting you much other than a slightly cleaner history and in return is far more difficult and error prone.

    If you want to merge in the target branch to make your Pull Request mergeable, you would add the original repository as a new remote, fetch from it, merge the main branch of that repository into your topic branch, fix any issues and finally push it back up to the same branch you opened the Pull Request on.

    One of the great things about Git is that you can do that continuously. If you have a very long-running project, you can easily merge from the target branch over and over again and only have to deal with conflicts that have arisen since the last time that you merged, making the process very manageable.

    Once you do that, the Pull Request will be automatically updated and re-checked to see if it merges cleanly.

    $ git remote add upstream https://github.com/schacon/blink
    #Add the original repository as a remote named “upstream”

    $ git fetch upstream
    #Fetch the newest work from that remote

    $ git merge upstream/master
    Auto-merging blink.ino
    CONFLICT (content): Merge conflict in blink.ino
    Automatic merge failed; fix conflicts and then commit the result.
    #Merge the main branch of that repository into your topic branch

    $ vim blink.ino
    $ git add blink.ino
    $ git commit
    #Fix the conflict that occurred

    $ git push origin slow-blink
    #Push back up to the same topic branch

    Command Description Example
    Cross-reference another Pull Request or an Issue
    by number
    All Pull Requests and Issues are assigned numbers and they are unique within the project. For example, you can’t have Pull Request #3 and Issue #3.

    If you want to reference any Pull Request or Issue from any other one, you can simply put # in any comment or description.

    You can also be more specific if the Issue or Pull request lives somewhere else;
    write username# if you’re referring to an Issue or Pull Request in a fork of the repository you’re in,
    or username/repo# to reference something in another repository.

    E.g., we rebased the branch,
    created a new pull request for it,
    and now we want to reference the old pull request from the new one.
    We also want to reference an issue in the fork of the repository
    and an issue in a completely different project:

    This PR replaces #2 as a rebased branch instead.
    You should also see tonyachon#1 and of course schacon/kidgloives#2
    Though nothing compares to https://github.com/schacon/kidgloves/issues/1

    Command Description Example
    Reference a commit by SHA-1
    You can reference commits in forks or other repositories in the same way you did with issues.

    You have to specify a full 40 character SHA-1,
    but if GitHub sees that in a comment,
    it will link directly to the commit.

    In Issue and Pull Request descriptions, comments, code comments and more,
    you can use what is called “GitHub Flavored Markdown”.

    Markdown is like writing in plain text but which is rendered richly.

    Command Description Example
    GitHub Flavored Markdown
    Task Lists

    a list of checkboxes of things you want to get done.

    Putting them into an Issue or Pull Request normally indicates things that you want to get done before you consider the item complete.

    This is often used in Pull Requests to indicate what all you would like to get done on the branch before the Pull Request will be ready to merge.

    The really cool part is that you can simply click the checkboxes to update the comment — you don’t have to edit the Markdown directly to check tasks off.

    GitHub will look for task lists in your Issues and Pull Requests
    and show them as metadata on the pages that list them out.

    E.g., if you have a Pull Request with tasks
    and you look at the overview page of all Pull Requests,
    you can see the progress bar of how far done it is.
    These are incredibly useful when you open a Pull Request early
    and use it to track your progress
    through the implementation of the feature.

    - [X] Write the code
    - [ ] Write all the tests
    - [ ] Document the code

    If included in the description of our Pull Request or Issue,
    we’ll see it rendered like Task lists rendered in a Markdown comment.

    Code Snippets

    add code snippets to comments

    To add a snippet of code you have to “fence” it in backticks.

    This is especially useful if you want to present something that you could try to do before actually implementing it as a commit on your branch.

    This is also often used to add example code of what is not working or what this Pull Request could implement.

    If you add a language name (e.g., java), GitHub will also try to syntax highlight the snippet.

    for(int i=0 ; i < 5 ; i++) { System.out.println("i is : " + i); } ```
    Quoting If you’re responding to a small part of a long comment, you can selectively quote out of the other comment by preceding the lines with the > character.

    Keyboard shortcut: highlight text in a comment that you want to directly reply to and hit the r key

    > Whether 'tis Nobler in the mind to suffer
    > The Slings and Arrows of outrageous Fortune,

    How big are these slings and in particular, these arrows?

    Emoji There is an emoji helper in GitHub.
    If you are typing a comment and you start with a : character, an autocompleter will help you find what you’re looking for.

    A great emoji cheat sheet

    I :eyes: that :bug: and I :cold_sweat:.

    :trophy: for :microscope: it.

    :+1: and :sparkles: on this :ship:, it's :fire::poop:!


    Images In addition to adding Markdown image links to comments, which can be difficult to find and embed URLs for, GitHub allows you to drag and drop images into text areas to embed them.

    Git Tagging

    Git Tagging

    Command Description Example
    git show tag-name For annotated tags shows tag data
    along with the commit that was tagged by
    the tagger information,
    the date the commit was tagged,
    and the annotation message.

    For lightweight tags shows just the commit
    with no extra information.

    git show v1.4
    git tag lists the tags in alphabetical order
    (Tags - specific points in a repository’s history
    marked as being important)
    git tag -l "pattern"

    git tag ‐‐list "pattern"

    searches for tags that match a particular pattern $ git tag -l "v1.8.5*"
    searches for 1.8.5 series tags of Git source repo

    Command Description Example
    git tag tagname A lightweight tag is very much like a branch that doesn’t change — it’s just a pointer to a specific commit.

    This is basically the commit checksum stored in a file — no other information is kept.

    Use if you want a temporary tag or for some reason don’t want to keep the other information.

    To create a lightweight tag, don’t supply any of the -a, -s, or -m options, just provide a tag name

    $ git tag v1.4-lw
    git tag -a tagname -m "message" Annotated tags, however, are stored as full objects in the Git database. They’re checksummed; contain the tagger name, email, and date; have a tagging message; and can be signed and verified with GNU Privacy Guard (GPG).

    It’s generally recommended that you create annotated tags so you can have all this information.

    The -m specifies a tagging message, which is stored with the tag. If you don’t specify a message for an annotated tag, Git launches your editor so you can type it in.

    git tag -a v1.4 -m "my version 1.4"
    git tag -a tagname commit-checksum Tagging after commit

    You can also tag commits after you’ve moved past them.

    To tag the commit, you specify the commit checksum (or part of it) at the end of the command

    $ git tag -a v1.2 9fceb02

    Command Description Example
    git push origin tagname By default, the git push command doesn’t transfer tags to remote servers.

    You will have to explicitly push tags to a shared server after you have created them.

    This process is just like sharing remote branches

    when someone else clones or pulls from your repository, they will get all your tags as well

    $ git push origin v1.5
    git push origin ‐‐tags Use If you have a lot of tags that you want to push up at once

    git push pushes both types of tags
    without distinguish between lightweight and annotated tags; there is no simple option that allows you to select just one type for pushing.

    $ git push origin ‐‐tags

    Command Description Example
    git tag -d tagname deletes a tag on your local repository
    without removing tag from any remote servers
    $ git tag -d v1.4-lw
    git push remote :refs/tags/tagname deletes tag from remote server

    (null value before the colon
    is being pushed to the remote tag name,
    effectively deleting it).

    $ git push origin :refs/tags/v1.4-lw
    git push origin ‐‐delete tagname deletes tag from remote server

    Command Description Example
    $ git checkout tag-name shows versions of files tag is pointing to

    this puts your repository in “detached HEAD” state,
    which has some ill side effects:

    if you make changes and then create a commit,
    the tag will stay the same,
    but your new commit won’t belong to any branch
    and will be unreachable,
    except by the exact commit hash.

    Thus, if you need to make changes 
    — say you’re fixing a bug on an older version
    — you will generally want to create a branch:
    $ git checkout -b version2 v2.0.0

    If you do this and make a commit,
    your version2 branch will be slightly different
    than your v2.0.0 tag
    since it will move forward with your new changes,
    so do be careful.

    $ git checkout 2.0.0

    Git Stashing

    Git Stash

    Command Description Example
    git stash list

    Command Description Example
    git stash save "description"

    Command Description Example
    git stash pop Bring stash back
    and remove from stash
    git stash apply Bring stash back and leave in stash

    Command Description Example
    git stash drop

    Configuring Git Settings

    Command Description Example
    $ git config ‐‐list ‐‐show-origin view all of your settings
    and where they are coming from
    git config ‐‐list list all the settings Git can find at that point

    You may see keys more than once,
    because Git reads the same key from different files
    (/etc/gitconfig and ~/.gitconfig, for example).

    In this case, Git uses the last value for each unique key it sees.

    $ git config ‐‐list ‐‐show-origin
    [config variable value]
    Since Git might read the same configuration variable
    value from more than one file,
    it’s possible that you have an unexpected value
    for one of these values and you don’t know why.

    In cases like that,
    you can query Git as to the origin for that value,
    and it will tell you which configuration file
    had the final say in setting that value

    $ git config ‐‐show-origin rerere.autoUpdate
    file:/home/johndoe/.gitconfig false
    git config [key] check what Git thinks a specific key’s value $ git config user.name
    John Doe

    Command Description Example
    git config ‐‐global alias.alias-name command If you don’t want to type the entire text of each of the Git commands, you can easily set up an alias for each command using git config.

    Git simply replaces the new command with whatever you alias it for.

    $ git config ‐‐global alias.ci commit
    instead of typing git commit, you just need to type git ci

    $ git config ‐‐global alias.co checkout
    $ git config ‐‐global alias.br branch
    $ git config ‐‐global alias.st status

    $ git config ‐‐global alias.alias-name 'command' creating new commands that you think should exist $ git config ‐‐global alias.unstage 'reset HEAD ‐‐'
    This makes the following two commands equivalent:
    $ git unstage fileA
    $ git reset HEAD ‐‐ fileA

    $ git config ‐‐global alias.last 'log -1 HEAD'
    see the last commit easily:
    $ git last

    If you want to run an external command,
    rather than a Git subcommand,
    start the command with a ! character.

    Useful if you write your own tools that work with a Git repository.

    $ git config ‐‐global alias.visual '!gitk'
    aliasing git visual to run gitk

    Command Description Example
    git config ‐‐global color.ui auto enables helpful colorization of command line output

    Command Description Example
    git config ‐‐global push.default matching push all matching branches
    All branches having the same name in both ends are considered to be matching
    git config ‐‐global push.default current push the current branch to a branch of the same name
    by default you will only push the current branch when you do git push
    git config ‐‐global push.default simple push the current branch to its upstream branch
    refuses to push if the upstream branch's name is different from the local one

    Leave a Reply or Comment

    Your email address will not be published. Required fields are marked *