VDone Demo VDone Demo
Home
  • Articles

    • JavaScript
  • Study Notes

    • JavaScript Tutorial
    • Professional JavaScript
    • ES6 Tutorial
    • Vue
    • React
    • TypeScript: Build Axios from Scratch
    • Git
    • TypeScript
    • JS Design Patterns
  • HTML
  • CSS
  • Technical Docs
  • GitHub Tips
  • Node.js
  • Blog Setup
  • Learning
  • Interviews
  • Miscellaneous
  • Practical Tips
  • Friends
About
Bookmarks
  • Categories
  • Tags
  • Archives
GitHub (opens new window)

Nikolay Tuzov

Backend Developer
Home
  • Articles

    • JavaScript
  • Study Notes

    • JavaScript Tutorial
    • Professional JavaScript
    • ES6 Tutorial
    • Vue
    • React
    • TypeScript: Build Axios from Scratch
    • Git
    • TypeScript
    • JS Design Patterns
  • HTML
  • CSS
  • Technical Docs
  • GitHub Tips
  • Node.js
  • Blog Setup
  • Learning
  • Interviews
  • Miscellaneous
  • Practical Tips
  • Friends
About
Bookmarks
  • Categories
  • Tags
  • Archives
GitHub (opens new window)
  • 手册

  • 文档笔记

    • Git Basics and Commands
      • Git Basics
        • Global Configuration
        • Checking Configuration
        • Getting Help
        • Initializing a Repository
        • Cloning a Remote Repository
        • Checking File Status
        • Adding to the Staging Area (Tracking Files)
        • Ignoring Files
        • Viewing Specific Changes
        • Committing Updates
        • Skipping the Staging Area
      • Git Basics - Viewing Commit History
      • Git Basics - Undoing Things
      • Git Basics - Working with Remotes
        • Viewing Remote Repositories
        • Adding a Remote Repository
        • Fetching and Pulling from Remotes
        • Pushing to a Remote Repository
        • Inspecting a Remote Repository
        • Renaming and Removing Remotes
      • Git Basics - Tagging
        • Listing Tags
        • Creating Tags
        • Annotated Tags
        • Lightweight Tags
        • Tagging Later
        • Sharing Tags
        • Deleting Tags
        • Checking Out Tags
      • Git Command Aliases
    • Git Branches - Branch Internals
    • Git Branch Creation and Merging - Branch Operations
    • Git Branch Management - Viewing Branches
    • Git Branching Workflows
    • Git Branches - Remote Branches
    • Git Branches - Rebasing
    • Git Tools - Revision Selection
    • Git Tools - Interactive Staging
    • Git Tools - Rewriting History
    • Git Tools - Reset Demystified
  • 《Git》学习笔记
  • 文档笔记
xugaoyi
2020-11-18
Contents

Git Basics and Commands

# Git Basics and Commands

Official documentation (Chinese): https://git-scm.com/book/zh/v2

This document is based on the official documentation. Please refer to the official documentation as the primary source.

# Git Basics

# Global Configuration

git config --global user.name 'your name'
git config --global user.email 'xxx@xx.com'
1
2

Introduce yourself to Git.

# Checking Configuration

git config --list
1

# Getting Help

# Get the global help manual
git help

# Get the detailed help manual for a specific command (both commands are equivalent)
git help <command>
git <command> --help # two dashes

# Get the concise help manual for a specific command
git <command> -h  # one dash
1
2
3
4
5
6
7
8
9

# Initializing a Repository

# Initialize a repository in the local directory
git init
1
2

If you cloned the project from a remote repository, the project is already an initialized git repository.

# Cloning a Remote Repository

# Clone
git clone <url>

# Clone and rename the directory
git clone <url> <name>
1
2
3
4
5

When you first clone a repository, all files in the working directory are tracked and in an unmodified state, because Git just checked them out and you have not edited them yet.

# Checking File Status

# View detailed status information
git status

# View concise status information
git status -s  # -s or --short
 M README # Modified but not staged (M on the right, red)
MM Rakefile # Modified, staged, then modified again (both staged and unstaged changes)
A  lib/git.rb # Newly added to the staging area, not committed
M  lib/simplegit.rb # Modified and staged (M on the left, green)
?? LICENSE.txt # Newly added, untracked
1
2
3
4
5
6
7
8
9
10
  • File statuses in a git directory include: whether tracked, whether modified, and whether staged.

  • A single dash indicates a shorthand flag, while two dashes indicate the full name.

# Adding to the Staging Area (Tracking Files)

# Add a file to the staging area (track the specified file)
git add <files>
1
2

The git add command takes a file or directory path as an argument; if the argument is a directory path, the command recursively tracks all files in that directory.

The add command adds files to the staging area, the commit command commits to the local repository, and the push command pushes to the remote repository.

# Ignoring Files

Add a file named .gitignore listing patterns for files to ignore.

*.[oa]  # Ignore files ending in .o or .a (typically produced during compilation)
*~      # Ignore files ending in ~ (typically backup copies from text editors)
1
2

The format rules for .gitignore are as follows:

  • All blank lines or lines starting with # are ignored by Git (comment character).

  • Standard glob patterns can be used, and they apply recursively throughout the working directory.

    Glob patterns are simplified regular expressions used by the shell.

  • Patterns can start with (/) to prevent recursion.

  • Patterns can end with (/) to specify a directory.

  • To negate a pattern and track files or directories that would otherwise be ignored, prefix the pattern with an exclamation mark (!).


  • An asterisk (*) matches zero or more characters.
  • [abc] matches any character listed in the brackets (in this example, it matches a, b, or c).
  • A question mark (?) matches exactly one character.
  • [0-9] matches all digits from 0 to 9. Using a dash between two characters in brackets indicates a range.
  • Two asterisks (**) match any intermediate directories, e.g., a/**/z matches a/z, a/b/z, or a/b/c/z, etc.
# Ignore all .a files
*.a

# But track lib.a, even though you are ignoring .a files above
!lib.a

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

# Ignore any directory named build
build/

# Ignore doc/notes.txt, but not doc/server/arch.txt
doc/*.txt

# Ignore all .pdf files in the doc/ directory and its subdirectories
doc/**/*.pdf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

GitHub has a very detailed list of .gitignore files for dozens of projects and languages, which you can find at https://github.com/github/gitignore.

# Viewing Specific Changes

git diff # Compare changes that have been modified but not yet staged.

git diff --staged # View staged changes that will be included in the next commit
1
2
3

git status only shows the status of file changes, not the specific content that was modified. Use git diff to see the exact changes.

# Committing Updates

git commit # Without arguments, opens the default text editor for you to enter a commit message

git commit -m 'commit message' # Use the -m flag to provide the commit message directly
1
2
3

Use git commit to commit updates. Before doing so, make sure all changes have been added to the staging area with git add.

# Skipping the Staging Area

git commit -a -m 'commit message'
1

Adding the -a option skips the git add step and commits all tracked files at once.

Note: This operation cannot commit untracked files.

# Git Basics - Viewing Commit History

git log
1

By default (without any arguments), git log lists all commits in reverse chronological order, with the most recent updates appearing first.

One item in the output is a long SHA-1 checksum string.

Use -p or --patch to view the specific differences of each commit:

git log -p -2 # -p shows the diff, -2 shows only the last 2 commits
1

--stat shows summary statistics for each commit

git log --stat
1

--pretty - This option allows you to display commit history in formats different from the default.

This option has some built-in sub-options. For example, oneline displays each commit on a single line, which is very useful when browsing a large number of commits. There are also short, full, and fuller options, which display information in similar formats but with varying levels of detail:

$ git log --pretty=oneline
ca82a6dff817ec66f44342007202690a93763949 changed the version number
085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7 removed unnecessary test
a11bef06a3f659402fe7563abf99ad00de2209e6 first commit
1
2
3
4

The most interesting option is format, which lets you customize the display format of records. This is particularly useful for later parsing and analysis since you know the output format will not change with Git updates:

$ 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
1
2
3
4

Common options for git log --pretty=format (opens new window) lists the commonly used format placeholders and their meanings.

When oneline or format is combined with the --graph log option, it becomes especially useful. This option adds ASCII art to visually represent your branch and merge history:

$ git log --pretty=format:"%h %s" --graph
* 2d3acf9 ignore errors from SIGCHLD on trap
*  5e3ee11 Merge branch 'master' of git://github.com/dustin/grit
|\
| * 420eac9 Added a method for getting the current branch.
* | 30e367c timeout code and tests
* | 5a09431 add timeout protection to grit
* | e1193f8 support for heads with slashes in them
|/
* d6016bc require time for xmlschema
*  11d191e Merge branch 'defunkt' into local
1
2
3
4
5
6
7
8
9
10
11

# Git Basics - Undoing Things

If you commit and then realize you forgot to stage certain changes, you can do the following:

$ git commit -m 'initial commit'
$ git add forgotten_file
$ git commit --amend # Recommit, resulting in only one commit record
1
2
3

You end up with only one commit -- the second commit replaces the result of the first.

For more undo operations, learn about the reset command.

# Git Basics - Working with Remotes

# Viewing Remote Repositories

git remote # Show only the name of the remote repository
git remote -v # Show the name + URL of the remote repository
1
2

# Adding a Remote Repository

 git remote add <remote-name> <url>
1

# Fetching and Pulling from Remotes

As just seen, to get data from a remote repository, you can run:

git fetch <remote>
1

This command accesses the remote repository and pulls down all data you don't have yet. After executing, you will have references to all branches from that remote repository, which you can merge or inspect at any time.

Note: The git fetch command only downloads data to your local repository -- it does not automatically merge or modify your current work. When ready, you must manually merge it into your work.

git pull
1

Use git pull to automatically fetch and then merge a remote branch into your current branch. This may be a more convenient workflow. By default, git clone automatically sets your local master branch to track the cloned remote repository's master branch (or whatever the default branch is named). Running git pull will usually fetch data from the originally cloned server and automatically attempt to merge it into your current branch.

# Pushing to a Remote Repository

git push <remote> <branch> # git push origin master
1

# Inspecting a Remote Repository

 git remote show <remote> # git remote show origin
1

View detailed information about a remote repository. This command lists which remote branch is automatically pushed to when you run git push on specific branches.

# Renaming and Removing Remotes

git remote rename <old-name> <new-name> # Rename
git remote remove paul <remote># Remove a remote repository
1
2

# Git Basics - Tagging

# Listing Tags

git tag # Full tag list
git tag -l "v2.0*" # Show only tags containing v2.0. Note the asterisk (*)
1
2

Both -l and --list work.

# Creating Tags

Git supports two types of tags: lightweight tags and annotated tags.

A lightweight tag is very much like a branch that doesn't change -- it's just a pointer to a specific commit.

An annotated tag is stored as a full object in the Git database. They are checksummed and contain the tagger's name, email, date, and a tagging message. They can also be signed and verified with GNU Privacy Guard (GPG). It is generally recommended to create annotated tags so you can have all this information. However, if you want a temporary tag, or for some reason don't want to keep this extra information, lightweight tags are also available.

# Annotated Tags

git tag -a v1.4 -m "my version 1.4" # -a means annotate, -m specifies the message
1

You can see the tag data along with the corresponding commit using git show:

git show v1.4
1

# Lightweight Tags

A lightweight tag is essentially the commit checksum stored in a file -- no other information is kept. To create a lightweight tag, don't supply the -a, -s, or -m options, just provide a tag name:

git tag v1.4-lw # No options needed
1

If you run git show on this tag, you won't see the extra tag information. The command just shows the commit information:

$ git show v1.4-lw
commit ca82a6dff817ec66f44342007202690a93763949
Author: Scott Chacon <schacon@gee-mail.com>
Date:   Mon Mar 17 21:52:11 2008 -0700
1
2
3
4

# Tagging Later

You can also tag past commits. Suppose the commit history looks like this:

$ git log --pretty=oneline
166ae0c4d3f420721acbb115cc33848dfcc2121a started write support
9fceb02d0ae598e95dc970b74767f19372d61af8 updated rakefile
8a5cbc430f1a9c3d00faaeffd07798508422908a updated readme
1
2
3
4

Now, suppose you forgot to tag the project at v1.2, which was at the "updated rakefile" commit. You can add the tag after the fact. To tag that commit, you need to specify the commit checksum (or partial checksum) at the end of the command:

$ git tag -a v1.2 9fceb02 # This creates an annotated tag
1

# Sharing Tags

The git push command doesn't transfer tags to remote servers by default. After creating tags, you must explicitly push them to a shared server. This process is just like sharing remote branches -- you can run git push origin <tagname>.

git push origin v1.5 # Explicitly push a tag to the remote repository
git push origin --tags # Push all tags not yet on the remote server at once
1
2

Now, when other people clone or pull from the repository, they will also get your tags.

# Deleting Tags

To delete a tag on your local repository, use git tag -d <tagname>. For example, you can delete a lightweight tag with:

$ git tag -d v1.4-lw
Deleted tag 'v1.4-lw' (was e7d5add)
1
2

Note that this does not remove the tag from any remote servers. You must use git push <remote> :refs/tags/<tagname> to update your remote repository:

The first variant is git push <remote> :refs/tags/<tagname>:

$ git push origin :refs/tags/v1.4-lw
To /git@github.com:schacon/simplegit.git
 - [deleted]         v1.4-lw
1
2
3

The meaning of this operation is to push an empty value before the colon to the remote tag name, effectively deleting it.

The second, more intuitive way to delete a remote tag is:

$ git push origin --delete <tagname>
1

# Checking Out Tags

If you want to view the versions of files a tag points to, you can use git checkout, although this puts your repository in a "detached HEAD" state -- which has some undesirable side effects:

$ git checkout 2.0.0
Note: checking out '2.0.0'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b <new-branch>

HEAD is now at 99ada87... Merge pull request #89 from schacon/appendix-final

$ git checkout 2.0-beta-0.1
Previous HEAD position was 99ada87... Merge pull request #89 from schacon/appendix-final
HEAD is now at df3f601... add atlas.json and cover image
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

In "detached HEAD" state, if you make changes and commit them, the tag will not change, but your new commit won't belong to any branch and will be unreachable except by the exact commit hash. Therefore, if you need to make changes -- say, to fix a bug in an older version -- you will generally need to create a new branch:

$ git checkout -b version2 v2.0.0
Switched to a new branch 'version2'
1
2

If you then make another commit, the version2 branch will move forward with your changes, making it slightly different from the v2.0.0 tag, so be careful.

# Git Command Aliases

Git doesn't automatically infer what command you want when you type a partial command. If you don't want to type the entire text of each Git command, you can easily set up an alias for each command using git config. Here are some examples:

$ git config --global alias.co checkout
$ git config --global alias.br branch
$ git config --global alias.ci commit
$ git config --global alias.st status
1
2
3
4

This means that when you need to type git commit, you only need to type git ci.

This technique is also useful when creating commands you think should exist. For example, to address the usability issue of unstaging files, you can add your own unstage alias to Git:

$ git config --global alias.unstage 'reset HEAD --'
1

This makes the following two commands equivalent:

$ git unstage fileA
$ git reset HEAD -- fileA
1
2

This looks much clearer. It is also common to add a last command like this:

$ git config --global alias.last 'log -1 HEAD'
1

This way, you can easily see the last commit:

$ git last
commit 66938dae3329c7aebe598c2246a8e6af90d04646
Author: Josh Goebel <dreamer3@example.com>
Date:   Tue Aug 26 19:48:51 2008 +0800

    test for current head

    Signed-off-by: Scott Chacon <schacon@example.com>
1
2
3
4
5
6
7
8

As you can see, Git simply replaces the alias with the corresponding command. However, maybe you want to run an external command rather than a Git subcommand. In that case, you can prefix the command with !. This is useful if you are writing your own tools to work with a Git repository. Here we demonstrate defining git visual as an alias for gitk:

$ git config --global alias.visual '!gitk'
1
Edit (opens new window)
#Git
Last Updated: 2026/03/21, 12:14:36
Git Command Mind Map
Git Branches - Branch Internals

← Git Command Mind Map Git Branches - Branch Internals→

Recent Updates
01
How I Discovered Disposable Email — A True Story
06-12
02
Animations in Grid Layout
09-15
03
Renaming a Git Branch
08-11
More Articles >
Theme by VDone | Copyright © 2026-2026 Nikolay Tuzov | MIT License | Telegram
  • Auto
  • Light Mode
  • Dark Mode
  • Reading Mode