☝️ Important
This material was borrowed from a third-party source.
Git console commands cheat sheet
General
Git is a version control system (for files). Something like the ability to save your progress in computer games (in Git, the equivalent of a game save is a commit). Important: adding files to a “save” is a two-step process: first we add the file to the index (git add), then we “save” it (git commit).
Any file in the directory of an existing repository may or may not be under version control (tracked and untracked).
Tracked files can be in 3 states: unmodified, modified, staged (ready to be committed).
The key to understanding
The key to understanding the git concept is knowing about the “three trees”:
- Working directory — the project’s file system (the files you work with).
- Index — the list of files and directories tracked by git, an intermediate storage for changes (editing, deleting tracked files).
- The
.git/directory — all the version control data for this project (the entire development history: commits, branches, tags, etc.).
A commit is a “save” (it stores the set of changes made in the working directory since the previous commit). A commit is immutable, it can’t be edited.
All commits (except the very first one) have one or more parent commits, since commits store changes relative to previous states.
The simplest workflow cycle
- Editing, adding, deleting files (the actual work).
- Staging/adding files to the index (telling git which changes need to be committed).
- Commit (recording the changes).
- Go back to step 1 or go to sleep.
Pointers
HEAD— a pointer to the current commit or to the current branch (that is, in any case, to a commit). Points to the parent of the commit that will be created next.ORIG_HEAD— a pointer to the commit you just movedHEADaway from (with thegit reset ...command, for example).- Branch (
master,developetc.) — a pointer to a commit. When a commit is added, the branch pointer moves from the parent commit to the new one. - Tags — simple pointers to commits. They don’t move.
Settings
Before starting work, you need to do some configuration:
git config --global user.name "Your Name" # set the name that will sign the commits
git config --global user.email "e@w.com" # set the email that will appear in the committer descriptionIf you’re on Windows:
git config --global core.autocrlf true # enable converting line endings from CRLF to LFSpecifying untracked files
Files and directories that shouldn’t be included in the repository are specified in the .gitignore file. Usually these are installed dependencies (node_modules/, bower_components/), the built output build/ or dist/, and similar things created during installation or when running the project. Each file or directory is listed on a new line, patterns can also be used.
Console
How to use the Bash console on Windows, basic commands.
Long output in the console: Vim
Calling some console commands leads to a very long console output (example: showing the full history of changes to a file with the command git log -p fileName.txt). In this case, the Vim editor is launched right in the console. It operates in several modes, of which you’ll be interested in insert mode (text editing) and normal (command) mode. To get from Vim back to the console, you need to type :q in command mode. To switch to command mode from any other mode: Esc.
If you need to type something, press i — this switches to text insert mode. If you need to save changes, switch to command mode and type :w.
Vim (some commands)
# Key presses
ESC — switch to command mode
i — switch to text edit mode
ZQ (hold Shift, press keys in sequence) — exit without saving
ZZ (hold Shift, press keys in sequence) — save and exit
```bash
# Key presses
ESC — switch to command mode
i — switch to text edit mode
ZQ (hold Shift, press keys in sequence) — exit without saving
ZZ (hold Shift, press keys in sequence) — save and exit
# Input in command mode
:q! — exit without saving
:wq — save the file and exit
:w filename.txt — save the file as filename.txtConsole commands
Create a new repository
git init # create a new project in the current directory
git init folder-name # create a new project in the specified directoryCloning a repository
# clone a remote repository into a directory of the same name
git clone https://github.com/cyberspacedk/Git-commands.git
# clone a remote repository into the "FolderName" directory
git clone https://github.com/cyberspacedk/Git-commands.git FolderName
# clone a repository into the current directory
git clone https://github.com:nicothin/web-design.git . Viewing changes
git status # show the repository state (tracked, modified, new files, etc.)
git diff # compare the working directory and the index (untracked files are IGNORED)
git diff --color-words # compare the working directory and the index, show word-level differences (untracked files are IGNORED)
git diff index.html # compare a file from the working directory and the index
git diff HEAD # compare the working directory and the commit HEAD points to (untracked files are IGNORED)
git diff --staged # compare the index and the commit at HEAD
git diff master feature # see what's been done in the feature branch compared to the master branch
git diff --name-only master feature # see what's been done in the feature branch compared to the master branch, show only file names
git diff master...feature # see what's been done in the feature branch since it diverged (its commit) from masterAdding changes to the index
git add . # add all new, modified, deleted files from the current directory and its subdirectories to the index
git add text.txt # add the specified file to the index (it was modified, deleted, or is a new file)
git add -i # launch an interactive shell to add only selected files to the index
git add -p # show new/modified files one at a time with their changes and ask whether to track/stage themRemoving changes from the index
git reset # remove all staged changes from the index (all changes remain in the working directory), the opposite of git add
git reset readme.txt # remove the changes of the specified file from the index (changes remain in the working directory)Discarding changes
git checkout text.txt # DANGEROUS: discard changes in the file, restore the file's state as it is in the index
git reset --hard # DANGEROUS: discard changes; restore what's in the commit HEAD points to (uncommitted changes are removed from the index and the working directory, untracked files stay in place)
git clean -df # remove untracked files and directoriesCommits
git commit -m "Name of commit" # record the staged changes in a commit (commit them), add a message
git commit -a -m "Name of commit" # stage tracked files (ONLY tracked, but NOT new files) and commit, add a messageUndoing commits and moving through history
All commits that have already been pushed to the remote repository should be undone with new commits (git revert), to avoid causing history problems for other project participants.
git revert HEAD --no-edit # create a new commit that undoes the changes of the last commit, without opening the message editor
git revert b9533bb --no-edit # same, but undoes the changes made by the commit with the specified hash (b9533bb)All the commands below can ONLY be run if the commits haven’t been pushed to the remote repository yet.
# WARNING! Dangerous commands, you can lose uncommitted changes
git commit --amend -m "Title" # "re-commit" the changes of the last commit, replace it with a new commit with a different message (move the current branch back one commit, keeping the working directory and index "as is", create a new commit with the data from the "undone" commit, but a new message)
git reset --hard @~ # move HEAD (and the branch) to the previous commit, make the working directory and index the same as they were at the time of the previous commit
git reset --hard 75e2d51 # move HEAD (and the branch) to the commit with the specified hash, make the working directory and index the same as they were at the time of the specified commit
git reset --soft @~ # move HEAD (and the branch) to the previous commit, but leave all changes in the working directory and index
git reset --soft @~2 # same, but move HEAD (and the branch) back 2 commits
git reset @~ # move HEAD (and the branch) to the previous commit, leave the working directory as is, make the index the same as it was at the time of the previous commit (more convenient than git reset --soft @~ if you need to reset the index)
# Almost like git reset --hard, but safer: you can't lose changes in the working directory
git reset --keep @~ # move HEAD (and the branch) to the previous commit, reset the index, but leave changes in the working directory if possible (if a file with changes was modified between commits, an error will be raised and the switch won't happen)Temporarily switching to another commit
git checkout b9533bb # switch to the commit with the specified hash (move HEAD to the specified commit, restore the working directory to the state at the time of this commit)
git checkout master # switch to the commit that master points to (move HEAD to the commit master points to, restore the working directory to the state at the time of this commit)Switching to another commit and continuing work from it
You’ll need to create a new branch starting from the specified commit.
git checkout -b new-branch 5589877 # create the new-branch branch, starting from the commit with hash 5589877 (move HEAD to the specified commit, restore the working directory to the state at the time of this commit, create a pointer to this commit (a branch) with the specified name)Restoring changes
git checkout 5589877 index.html # restore the specified file in the working directory to its state at the time of the specified commit (and add this change to the index) (git reset index.html to remove it from the index, but keep the changes in the file)Copying a commit (transferring commits)
git cherry-pick 5589877 # copy the changes from the specified commit onto the active branch, commit these changes
git cherry-pick master~2..master # copy the changes from master (the last 2 commits) onto the active branch
git cherry-pick -n 5589877 # copy the changes from the specified commit onto the active branch, but DON'T COMMIT (implies we'll commit it ourselves later)
git cherry-pick master..feature # copy the changes from all commits of the feature branch onto the active branch, starting from when it diverged from master (similar to a branch merge, but this copies changes rather than merging), commit these changes; this may cause a conflict
git cherry-pick --abort # abort a conflicting commit transfer
git cherry-pick --continue # continue a conflicting commit transfer (will only work after the conflict is resolved)Deleting a file
git rm text.txt # delete a tracked unmodified file and stage this change
git rm -f text.txt # delete a tracked modified file and stage this change
git rm -r log/ # delete all contents of the tracked log/ directory and stage this change
git rm ind* # delete all tracked files whose name starts with "ind" in the current directory and stage this change
git rm --cached readme.txt # remove a staged file from tracking (THE FILE STAYS IN PLACE) (often used for files accidentally added to tracking)Moving/renaming files
For git, there is no such thing as renaming. A rename is treated as deleting the old file and creating a new one. The fact of renaming can only be detected after staging the change.
git mv text.txt test_new.txt # rename the file "text.txt" to "test_new.txt" and stage this change
git mv readme_new.md folder/ # move the file readme_new.md to the folder/ directory (must already exist) and stage this changeCommit history
To exit long log output: q.
git log master # show commits on the specified branch
git log -2 # show the last 2 commits on the active branch
git log -2 --stat # show the last 2 commits and stats for the changes they made
git log -p -22 # show the last 22 commits and the line-level diff they introduced
git log --graph -10 # show the last 10 commits with an ASCII representation of branching
git log --since=2.weeks # show commits from the last 2 weeks
git log --after '2018-06-30' # show commits made after the specified date
git log index.html # show the change history of the file index.html (commits only)
git log -5 index.html # show the change history of the file index.html, last 5 commits (commits only)
git log -p index.html # show the change history of the file index.html (commits and changes)
git log -G'myFunction' -p # show all commits that changed lines containing myFunction (a regular expression in quotes)
git log -L '/<head>/','/<\/head>/':index.html # show the changes between the specified regular expressions in the specified file
git log --grep fix # show commits whose description contains the substring fix (case-sensitive, only commits on the current branch)
git log --grep fix -i # show commits whose description contains the substring fix (case-INsensitive, only commits on the current branch)
git log --grep 'fix(ing|me)' -P # show commits whose description matches the regular expression (only commits on the current branch)
git log --pretty=format:"%h - %an, %ar : %s" -4 # show the last 4 commits with formatted output
git log --pretty=format:"%h %ad | %s%d [%an]" --graph --date=short # my output format, hanging off a shell alias
git log master..branch_99 # show commits from the branch_99 branch that aren't merged into master
git log branch_99..master # show commits from the master branch that aren't merged into branch_99
git log master...branch_99 --boundary -- graph # show commits from the specified branches, starting from their divergence point (the divergence commit will be shown)git show 60d6582 # show the changes from the commit with the specified hash
git show HEAD~ # show data about the previous commit on the active branch
git show @~ # same as above
git show HEAD~3 # show data about the commit that was 3 commits ago
git show my_branch~2 # show data about the commit that was 2 commits ago on the specified branch
git show @~:index.html # show the content of the specified file at the time of the previous (from HEAD) commit
git show :/"footer" # show the newest commit whose description contains the specified word (from any branch)Who wrote a line
git blame README.md --date=short -L 5,8 # show lines 5-8 of the specified file and the commits in which the lines were addedHistory of pointer changes (branches, HEAD)
git reflog -20 # show the last 20 changes of the HEAD pointer position
git reflog --format='%C(auto)%h %<|(20)%gd %C(blue)%cr%C(reset) %gs (%s)' -20 # same, but with how long ago the actions happenedBranches
git branch # show the list of branches
git branch -v # show the list of branches and the last commit in each
git branch new_branch # create a new branch with the specified name at the current commit
git branch new_branch 5589877 # create a new branch with the specified name at the specified commit
git branch -f master 5589877 # move the master branch to the specified commit
git branch -f master master~2 # move the master branch back 2 commits
git checkout new_branch # switch to the specified branch
git checkout -b new_branch # create a new branch with the specified name and switch to it
git checkout -B master 5589877 # move the branch with the specified name to the specified commit and switch to it
git merge hotfix # merge the data from the hotfix branch into the branch we're on
git merge hotfix -m "Hotfix" # merge the data from the hotfix branch into the branch we're on (with the specified merge commit message)
git merge hotfix --log # merge the data from the hotfix branch into the branch we're on, show the commit message editor, add the messages of the merged commits to it
git merge hotfix --no-ff # merge the data from the hotfix branch into the branch we're on, forbid a simple pointer move, the changes from hotfix will "remain" as such, and only a merge commit will appear on the active branch
git branch -d hotfix # delete the hotfix branch (used if its changes have already been merged into the main branch)
git branch --merged # show branches already merged with the active one
git branch --no-merged # show branches not merged with the active one
git branch -a # show all existing branches (including on remote repositories)
git branch -m old_branch_name new_branch_name # rename the local branch old_branch_name to new_branch_name
git branch -m new_branch_name # rename the CURRENT local branch to new_branch_name
git push origin :old_branch_name new_branch_name # apply the rename on the remote repository
git branch --unset-upstream # finish the rename processTags
git tag v1.0.0 # create a tag with the specified name at the commit HEAD points to
git tag -a -m 'To production!' v1.0.1 master # create an annotated tag on the commit the master branch points to
git tag -d v1.0.0 # delete the tag(s) with the specified name(s)
git tag -n # show all tags, and 1 line of the commit message they point to
git tag -n -l 'v1.*' # show all tags starting with 'v1.*'Temporarily saving changes without committing
git stash # temporarily save uncommitted changes and remove them from the working directory
git stash pop # restore the changes saved by git stash to the working directoryRemote repositories
There are two common ways to link a remote repository to a local one: via HTTPS and via SSH. If you don’t have SSH configured (or don’t know what it is), link the remote repository via HTTPS (the address of the repository being linked should start with https://).
git remote -v # show the list of remote repositories linked to the local one
git branch -r # show remote branches
git branch -a # show all branches (local and remote)
git remote remove origin # remove the link to the remote repository with the short name origin
git remote add origin https://github.com:nicothin/test.git # add a remote repository (with short name origin) with the specified URL
git remote rm origin # remove the link to the remote repository
git remote show origin # get data about the remote repository with the short name origin
git fetch origin # download all branches from the remote repository (with short name origin), but don't merge them with your own branches
git fetch origin master # same, but only the specified branch is downloaded
git checkout --track origin/github_branch # create a local branch github_branch (with data taken from the remote repository with short name origin, branch github_branch) and switch to it
git push origin master # push the data of your master branch to the remote repository (with short name origin)
git pull origin # merge changes from the remote repository (all branches)
git pull origin master # merge changes from the remote repository (only the specified branch)Merge conflict
Consider this situation: there’s a master branch and a feature branch. Both branches have commits made after they diverged. We try to merge the feature branch into master (git merge feature), and get a conflict, because both branches have changes to the same line in the index.html file.
When a conflict occurs, the repository is in an interrupted merge state. You need to leave only the needed code in the conflicting spots in the files, stage the changes, and commit.
git merge feature # merge the changes from the feature branch into the active branch
git merge-base master feature # show the hash of the last common commit for the two specified branches
git checkout --ours index.html # keep the state of the branch we're merging INTO in the conflicting file (index.html) (in the example — from the master branch)
git checkout --theirs index.html # keep the state of the branch we're merging FROM in the conflicting file (index.html) (in the example — from the feature branch)
git checkout --merge index.html # show a comparison of the contents of the merged branches in the conflicting file (index.html) (for manual editing)
git checkout --conflict=diff3 --merge index.html # show a comparison of the contents of the merged branches in the conflicting file (index.html), plus what was at the conflict location in the commit where the merged branches divergedgit reset --hard # abort this interrupted merge, restore the working directory and index to how they were at the commit HEAD points to, and I'll go cry a little
git reset --merge # abort this interrupted merge, but keep changes that weren't committed before the merge (for the case when the merge is done on a non-clean status)
git reset --abort # same as the line above“Moving” a branch
You can “move” the point where some branch diverges from the main branch to an arbitrary commit. This is needed so that some changes made in the main branch (already after the “moved” branch diverged) appear in the “moved” branch.
You can’t “move” a branch if it’s already been pushed to a remote repository.
git rebase master # transfer all commits (create copies of them) of the active branch as if the active branch had diverged from master at master's current tip (often causes conflicts)
git rebase --onto master feature # transfer the commits of the active branch onto master, starting from the point where the active branch diverged from the feature branch
git rebase --abort # abort a conflicting rebase, restore the working directory and index to the state before the rebase started
git rebase --continue # continue a conflicting rebase (will only work after resolving the conflict and staging that resolution)How to undo a rebase
git reflog feature -2 # look at the log of movements of the branch that was rebased (in this example — feature), find the last commit BEFORE the rebase, that's where the branch pointer needs to be moved
git reset --hard feature@{1} # move the feature branch pointer back one commit, update the working directory and indexMiscellaneous
git archive -o ./project.zip HEAD # create an archive with the project's file structure at the specified path (the repository state corresponding to the HEAD pointer)Examples
Building a collection of simple and complex working examples.
Getting started
Creating a new repository, the first commit, linking a remote repository on github.com, pushing changes to the remote repository.
# the sequence of actions is:
# the project directory has been created, we're in it
git init # create a repository in this directory
touch readme.md # create the readme.md file
git add readme.md # add the file to the index
git commit -m "Start" # create a commit
git remote add origin https://github.com:nicothin/test.git # add a previously created empty remote repository
git push -u origin master # push the data from the local repository to the remote one (to the master branch)“Making changes” to a commit
Only if the commit hasn’t already been pushed to the remote repository.
# the sequence of actions is:
subl inc/header.html # edit and save the "header" markup
git add inc/header.html # stage the modified file
git commit -m "Removed phone number from the header" # make the commit
# WARNING: the commit hasn't been pushed to the remote repository yet
# we realize we needed to do something else in this commit.
subl inc/header.html # make changes
git add inc/header.html # stage the modified file (git add . also works)
git commit --amend -m "\"Header\": task #34 completed" # redo the commitWorking with branches
There’s a master (public version of the site), we’re doing a large-scale task (redo the “header” markup), but along the way there’s a need to fix a critical bug (wrong contact listed in the “footer”).
# the sequence of actions is:
git checkout -b new-page-header # create a new branch for the "header" change task and switch to it
subl inc/header.html # edit the "header" markup
git commit -a -m "New header: logo change" # make a commit (work is not yet finished)
# now it turns out there's a bug with the contact in the "footer"
git checkout master # go back to the master branch
subl inc/footer.html # fix the bug and save the "footer" markup
git commit -a -m "Fixed footer contact" # make a commit
git push # push the quick critical fix commit to master on the remote repository
git checkout new-page-header # switch back to the new-page-header branch to continue work on the "header"
subl inc/header.html # edit and save the "header" markup
git commit -a -m "New header: navigation change" # make a commit ("header" work is finished)
git checkout master # switch to the master branch
git merge new-page-header # merge the changes from the new-page-header branch into master
git branch -d new-page-header # delete the new_page_header branchWorking with branches, merging and reverting to the pre-merge state
There was a fix branch, where a bug was being fixed. Fixed it, merged fix into master. But then it turned out this fix breaks some functionality. We need to roll master back to the state before the merge (having the bug is less critical than breaking functionality).
# we're on the fix branch, the bug has already been "fixed"
git checkout master # switch to master
git merge fix # merge the changes from fix into master
# we see a problem: some functionality is broken
git checkout fix # switch to fix (while we're on master, git won't let us move it)
git branch -f master ORIG_HEAD # move the master branch to the commit stored in ORIG_HEAD (the one master pointed to before merging fix)Working with branches, merge conflict
There’s a master branch (public version of the site); in two parallel branches (branch-1 and branch-2), the same spot in the same file was edited; the first branch (branch-1) has been merged into master, and attempting to merge the second causes a conflict.
# the sequence of actions is:
git checkout master # switch to the master branch
git checkout -b branch-1 # create the branch-1 branch, based on the master branch
subl . # edit and save files
git commit -a -m "Fix 1" # commit
git checkout master # go back to the master branch
git checkout -b branch-2 # create the branch-2 branch, based on the master branch
subl . # edit and save files
git commit -a -m "Fix 2" # commit
git checkout master # go back to the master branch
git merge branch-1 # merge the changes from branch-1 into the current branch (master), success (auto-merge)
git merge branch-2 # merge the changes from branch-2 into the current branch (master), auto-merge CONFLICT
# Automatic merge failed; fix conflicts and then commit the result.
subl . # in the conflicting files, choose the sections to keep, save
git commit -a -m "Resolve conflict" # commit the conflict resolution resultSyncing a fork repository with the upstream repository
There’s some repository on github.com, we forked it, and added some changes. The original (upstream) repository has since been updated. Task: pull the changes from the upstream repository (that were made there after we forked it).
# the sequence of actions is:
git remote add upstream https://github.com:address.git # add a remote repository: short name — upstream, URL of the upstream repository
git fetch upstream # pull all branches from the upstream repository, but don't merge them with our own yet
git checkout master # switch to our own repository's master branch
git merge upstream/master # merge the pulled master branch of the upstream remote into our own master branchMistake: committed to master, but realized it should have been committed to a new branch
IMPORTANT: this will only work if the commit hasn’t been pushed to the remote repository yet.
# the sequence of actions is:
# made changes, staged them, committed to master, but HAVEN'T PUSHED YET (didn't run git push)
git checkout -b new-branch # create a new branch from master
git checkout master # switch to master
git reset HEAD~ --hard # move the master branch pointer back 1 commit
git checkout new-branch # switch back to the new branch to continue workingNeed to restore a file’s contents to the state from some commit (the commit hash is known)
# the sequence of actions is:
git checkout f26ed88 -- index.html # restore the specified file in the working directory to its state at the specified commit, add this change to the index
git commit -am "Navigation fixs" # make a commitAny action with github (or another remote service) asks for a login and password
This is specifically about being asked for a login + password pair, not a passphrase. This happens because by default git won’t save the password for accessing the repository over HTTPS.
Simple solution: tell git to cache your password.
.gitattributes
* text=auto
*.html diff=html
*.css diff=css
*.scss diff=css👨💻And…
Don’t forget about our Telegram channel 📱 and chat
Or maybe you want to become a co-author? Then click here🔗
💬 All the best ✌️
That should be it. If not, check the logs 🙂


