Skip to main content

Git Tutorial

Free2015-05-19#Tool#git指南#git教程#git入门#github

A concise and comprehensive GitHub tutorial, including explanations of various functions needed in daily work and a command quick reference table

Git Tutorial

Written at the Beginning

A little history, those who don't like it please click here to skip

By 2002, the Linux system had already developed for ten years. The codebase was so large that Linus found it difficult to continue managing it manually. The community brothers also expressed strong dissatisfaction with this method. So Linus chose a commercial version control system BitKeeper. BitMover Company, the owner of BitKeeper, out of humanitarian spirit, authorized the Linux community to use this version control system for free.

The stable and united situation was broken in 2005. The reason was that the Linux community gathered many talented people, inevitably acquiring some Jianghu habits from Liangshan heroes. Andrew, who developed Samba, attempted to crack the BitKeeper protocol (he wasn't the only one doing this). BitMover Company discovered it (good monitoring work!), so BitMover Company got angry and wanted to take back the free usage rights of the Linux community.

Linus could apologize to BitMover Company and guarantee strict management of the brothers in the future. Hmm, that's impossible. The actual situation was like this:

Linus spent two weeks writing a distributed version control system in C by himself, this is Git! Within a month, the Linux system source code was already managed by Git! How is awesome defined? Everyone can experience it.

Git quickly became the most popular distributed version control system, especially in 2008 when the GitHub website went online. It provides free Git storage for open source projects. Countless open source projects began migrating to GitHub, including jQuery, PHP, Ruby, and so on.

Zero. Additional Questions

1. vim displays Chinese garbled text

Using vim directly from the command line will display Chinese garbled text, and using QQ Pinyin input method inside vim cannot input certain Chinese characters, for example, the 'wen' in Chinese 'wen', and the 'wu' in 'wu fa' will become 1

The utf8 garbled text problem has not been resolved yet (all solutions found cannot fix it), recommend not editing directly with vim

2. MINGW32 doesn't support copy/paste by default, needs manual setup

  1. Right-click title bar, select [Properties]

  2. Select [Options]

  3. Check [QuickEdit Mode Q]

  4. [OK]-[OK]

Settings take effect immediately, supports copy/paste:

  • Copy: Left-click drag to select, then right-click completes copy

  • Paste: Right-click inside the window

If you have questions please check ChinaUnix Blog: mingw copy/paste under windows

I. Install git

For methods to install git on Windows/Mac/Linux please check Liao Xuefeng's Official Website: Install Git

P.S. Senior Liao Xuefeng's git tutorial is very good, but you certainly don't have patience to read from beginning to end, but it doesn't matter, because I have read it, and will summarize it without nonsense as much as possible

II. Local Operations

1. Create Repository

  1. First find a nice folder, cd into it, prepare to create a repository (Repository) inside

P.S. Because git command line tool is actually a simplified Linux virtual machine, supports Shell commands. If you remember some Linux commands you will use it more smoothly. For common Shell commands please check Cnblogs: Common file and directory operation commands (reprint)

  1. Initialize a Git repository, use git init command

Can initialize current directory as git repository, actually just automatically generating some git management information under the directory

  1. Create new file

Create new file under this directory, command line touch or resource manager right-click create both work

  1. Add file to Git repository, in two steps:

    1. Use command git add <file> to put file into staging area, note, can use repeatedly multiple times, add multiple files;

    2. Use command git commit to submit staging area modifications, complete.

P.S. Files created under folder and file content additions/deletions/modifications are not automatically synced like synchronized cloud drive, need add-commit to create a new version

2. Daily Work

  1. Check status

To master workspace status at any time, use git status command.

If git status tells you files have been modified, use git diff to view modification content.

  1. Version backward and forward

The version HEAD points to is the current version, therefore, Git allows us to shuttle between version history, use command git reset --hard commit_id.

Before shuttling, use git log to view commit history, to determine which version to retreat to.

To return to future, use git reflog to view command history, to determine which future version to return to.

  1. Revert modifications

    • Scenario 1: When you mess up content of a file in workspace, want to directly discard workspace modifications, use command git checkout -- file.

    • Scenario 2: When you not only mess up content of a file in workspace, but also added to staging area, want to discard modifications, in two steps, first step use command git reset HEAD file, returns to Scenario 1, second step operate per Scenario 1.

    • Scenario 3: When already submitted inappropriate modifications to repository, want to revert this commit, refer to version retreat section, but premise is not pushed to remote repository.

  2. Delete file

Command git rm is used to delete a file. If a file has already been committed to repository, then you never need to worry about accidental deletion, but be careful, you can only restore file to latest version, you will lose content you modified after most recent commit.

  1. Operate branches

In actual development, we should follow several basic principles for branch management:

First, master branch should be very stable, that is, only used for releasing new versions, usually cannot work on it;

So where to work? Work all on dev branch, that is, dev branch is unstable, at some time, for example when 1.0 version releases, then merge dev branch to master, release 1.0 version on master branch;

You and your partners all work on dev branch, everyone has their own branch, occasionally merge to dev branch is enough.

When merging branches, adding --no-ff parameter can use normal mode merge, merged history has branches, can see merges were done, while fast forward merge cannot see merges were done. For example: git merge --no-ff -m "merge with no-ff" dev

Specific commands:

-  View branches: `git branch`

-  Create branch: `git branch <name>`

-  Switch branch: `git checkout <name>`

-  Create+switch branch: `git checkout -b <name>`

-  Merge some branch to current branch: `git merge <name>`

-  Delete branch: `git branch -d <name>`

When Git cannot automatically merge branches, must first resolve conflicts. After resolving conflicts, then commit, merge complete.

Git uses <<<<<<<, =======, >>>>>>> to mark content from different branches, manually modify to eliminate conflicts then add-commit is fine

Use git log --graph command can see branch merge diagram

  1. Handle bugs

When fixing bugs, we create new bug branch for fixing, then merge, finally delete;

When current work is not completed, first stash work scene with git stash, then go fix bug, after fixing, then git stash pop, return to work scene.

  1. Develop new features

Developing a new feature, best create a new branch;

If want to discard a branch that hasn't been merged, can use git branch -D <name> to force delete.

3. Humanized Configuration Options

  1. Ignore special files

When ignoring certain files, need to write .gitignore;

.gitignore file itself should be placed in repository, and can do version management on .gitignore

  1. Set command aliases

Widely accepted aliases (similar to macros, used to protect fingers):

-  st means status, command `git config --global alias.st status`

-  Use co for checkout, command `git config --global alias.co checkout`

-  ci means commit, command `git config --global alias.ci commit`

-  br means branch, command `git config --global alias.br branch`

3. Delete aliases

Each repository's Git configuration file is placed in .git/config file, aliases are after [alias], to delete alias, directly delete corresponding line is fine

Global Git configuration file is placed in ~/gitconfig file, can directly edit

  1. Other configuration options

There are many customizable parts, for example command output color scheme (filename highlighting etc.)

4. Setup git server

For detailed steps please check Liao Xuefeng's Official Website: Setup Git Server

III. Remote Operations

Remote operations refer to local project and github project syncing occasionally

0. Preparation work

Need to register github account, create repository, setup public key etc., specifics please check Liao Xuefeng's Official Website: Add Remote Repository

1. Associate remote repository

To associate a remote repository, use command git remote add origin git@server-name:path/repo-name.git;

After associating, use command git push -u origin master to first push all content of master branch;

Thereafter, after each local commit, whenever necessary, can use command git push origin master to push latest modifications;

One of the biggest benefits of distributed version control system is working locally completely doesn't need to consider existence of remote repository, that is, can work normally with or without internet connection, while SVN refuses to work when not connected to internet! When there is network, then push local commits to complete synchronization, so convenient!

2. Clone remote repository

To clone a repository, first must know repository address, then use git clone command to clone.

Git supports multiple protocols, including https, but native git protocol through ssh support is fastest.

3. Multi-person collaboration

View remote repository information, use git remote -v;

Locally created branches if not pushed to remote, are invisible to others;

Push branch from local, use git push origin branch-name, if push fails, first use git pull to fetch remote new commits;

Create branch corresponding to remote branch locally, use git checkout -b branch-name origin/branch-name, local and remote branch names best be consistent;

Establish association between local branch and remote branch, use git branch --set-upstream branch-name origin/branch-name;

Fetch branch from remote, use git pull, if there are conflicts, must handle conflicts first.

4. Use tags

Tags are a snapshot of repository, commonly used to mark current version before new version release

  1. Create tags

Command git tag <name> is used to create a new tag, defaults to HEAD, can also specify a commit id;

git tag -a <tagname> -m "blablabla..." can specify tag information;

git tag -s <tagname> -m "blablabla..." can use PGP signed tags;

Command git tag can view all tags.

  1. Operate tags

Command git push origin <tagname> can push a local tag;

Command git push origin --tags can push all unpushed local tags;

Command git tag -d <tagname> can delete a local tag;

Command git push origin :refs/tags/<tagname> can delete a remote tag.

5. fork sb on github

P.S. fork should be taken from Linux Shell command fork (copy current process, obtained child process and parent process don't affect each other), used to transfer other people's project repository to your own github, afterwards are mutually independent

On GitHub, can arbitrarily Fork open source repositories;

You own read/write permissions of forked repository;

Can push pull request to official repository to contribute code.

6. Common remote operations

  1. Get remote project git clone git@github.com:ayqy/git-helloworld.git, will create project folder under current directory

  2. Online modifications, get to local through git pull origin master

  3. Local modifications, upload sync through git push -u origin master (note to add-commit first)

IV. Common Commands

  • mkdir: XX (Create an empty directory XX refers to directory name)

  • pwd: Display current directory path.

  • cat XX: View XX file content

  • git init: Turn current directory into manageable git repository, generate hidden .git file.

  • git add XX: Add xx file to staging area.

  • git commit –m "XX": Commit file –m followed by comment.

  • git status: View repository status

  • git diff XX: View what content XX file modified

  • git log: View history records

  • git reset --hard HEAD^ or git reset --hard HEAD~: Retreat to previous version

P.S. If want to retreat to 100 versions, use git reset --hard HEAD~100

  • git reflog: View history record version id

  • git checkout -- XX: Revoke all modifications of XX file in workspace.

  • git rm XX: Delete XX file

  • git remote add origin https://github.com/ayqy/test.git: Associate a remote repository

  • git push –u(first time need -u afterwards not needed) origin master: Push current master branch to remote repository

  • git clone https://github.com/ayqy/test.git: Clone from remote repository

  • git checkout –b dev: Create dev branch and switch to dev branch

  • git branch: View all current branches

  • git checkout master: Switch back to master branch

  • git merge dev: Merge dev branch on current branch

  • git branch –d dev: Delete dev branch

  • git branch name: Create branch

  • git stash: Hide current work wait until restore scene later to continue work

  • git stash list: View all hidden file list

  • git stash apply: Restore hidden files, but content not deleted

  • git stash drop: Delete files

  • git stash pop: Restore files and also delete files

  • git remote: View remote repository information

  • git remote –v: View remote repository detailed information

  • git push origin master: Git will push master branch to remote branch corresponding to remote repository

  • git push origin :branch-name: Space before colon cannot be missing, principle is pushing an empty branch to server, equivalent to deleting that branch

  • git push --force origin master: Used when wanting local old version to overwrite latest version during version retreat, will delete new version log records, no traces

V. Complete Commands

1. CREATE

  • Clone an existing repository

    git clone ssh://user@domain.com/repo.git

  • Create a new local repository

    git init

2. LOCAL CHANGES

  • Changed files in your working directory

    git status

  • Changes to tracked files

    git diff

  • Add all current changes to the next commit

    git add .

  • Add some changes in to the next commit

    git add -p <file>

  • Commit all local changes in tracked files

    git commit -a

  • Commit previously staged changes

    git commit

  • Change the last commit Don't amend published commits!

    git commit --amend

3. COMMIT HISTORY

  • Show all commits, starting with newest

    git log

  • Show changes over time for a specific file

    git log -p <file>

  • Who changed what and when in

    git blame <file>

4. BRANCHES & TAGS

  • List all existing branches

    git branch -av

  • Switch HEAD branch

    git checkout <branch>

  • Create a new branch based on your current HEAD

    git branch <new-branch>

  • Create a new tracking branch based on a remote branch

    git checkout --track <remote/branch>

  • Delete a local branch

    git branch -d <branch>

  • Mark the current commit with a tag

    git tag <tag-name>

5. UPDATE & PUBLISH

  • List all currently configured remotes

    git remote -v

  • Show information about a remote

    git remote show <remote>

  • Add new remote repository, named

    git remote add <shortname> <url>

  • Download all changes from , but don't integrate into HEAD

    git fetch <remote>

  • Download changes and directly merge/integrate into HEAD

    git pull <remote> <branch>

  • Publish local changes on a remote

    git push <remote> <branch>

  • Delete a branch on the remote

    git branch -dr <remote/branch>

  • Publish your tags

    git push --tags

6. MERGE & REBASE

  • Merge into your current HEAD

    git merge <branch>

  • Rebase your current HEAD onto Don't rebase published commits!

    git rebase <branch>

  • Abort a rebase

    git rebase --abort

  • Continue a rebase after resolving conflicts

    git rebase --continue

  • Use your configured merge tool to solve conflicts

    git mergetool

  • Use your editor to manually solve conflicts and (after resolving) mark file as resolved

    git add <resolved-file>

    git rm <resolved-file>

7. UNDO

  • Discard all local changes in your working directory

    git reset --hard HEAD

  • Discard local changes in a specific file

    git checkout HEAD <file>

  • Revert a commit (by producing a new commit with contrary changes)

    git revert <commit>

  • Reset your HEAD pointer to a previous commit

    …and discard all changes since then: git reset --hard <commit>

    …and preserve all changes as unstaged changes: git reset <commit>

    …and preserve uncommitted local changes: git reset --keep <commit>

Reference Materials

Comments

No comments yet. Be the first to share your thoughts.

Leave a comment