Git
Li Wei
Title: Git
Preface
Command map:
Help documentation:
Branch learning:
Command quick reference:
| Command | Description |
|---|---|
git config --global user.name |
Set user name (signature) |
git config --global user.email |
Set user email (signature) |
Note: Using the
--globaloption writes to the.gitconfigfile in your home directory, so all of your projects will use this information by default. To use a different name or email for a specific project, omit--global; the new settings are saved in that project's.git/configfile. | |git init| Initialize a local repository | |git status| View repository status | |git add <filename>| Add file to the staging area (git add .adds everything) | |git rm --cached <filename>| Unstage/remove a file from the staging area (git rm --cached *unstage all) | |git commit -m "log message"<filename>| Commit to the local repository (omit filename to commit everything) | |git commit --amend| Amend the commit message | |git reflog| Show all operation records, including commits and resets | |git log| Show all committed versions (does not include deleted commits or reset actions) | Note:git reflogis often used to recover from local mistakes. Example: after committing a wrong change, you reset withgit reset --hard HEAD^, which also rolls back the working directory. If you later realize the previous commit was correct, you can find its hash in the reflog and reset to it.git logwould no longer show that commit. | |git reset --hard <hash>| Hard reset (travel to a specific version) | |git reset --soft <hash>| Soft reset (travel to a specific version) | Hard reset: The local code is overwritten by the specified commit—use with caution! It discards workspace changes, undoes commits, and undoesgit add .. After this, the state is exactly as after the previous commit.
Soft reset: The workspace files stay unchanged; only the Git index is moved back to the state before the commit. It undoes the commit but keeps the staged changes.git reset --soft HEAD^: a major use‑case—undo a commit without undoinggit add .. | |git branch <branch-name>| Create a branch | |git branch -v| List branches | |git checkout <branch-name>| Switch branches | |git merge <branch-name>| Merge the specified branch into the current one (may cause conflicts that need manual resolution) | |git remote -v| List all remote aliases | |git remote add <alias> <remote‑url>| Add a remote with an alias | |git push <alias> <branch>| Push local branch to the remote repository | |git clone <remote‑url>| Clone a remote repository locally | |git pull <remote‑alias> <remote‑branch>| Fetch the latest remote branch and merge it into the current local branch (may cause conflicts) |
Overview
Version Control Systems
SVN is a centralized version control system: the repository lives on a central server, and developers work on their own machines. They first pull the latest version from the server, develop locally, then push their changes back to the server.
Drawbacks of centralized VCS: single point of failure, poor fault tolerance.
Git is a Distributed Version Control System (DVCS) and has two kinds of repositories:
- Local repository: the Git repo on a developer’s own computer
- Remote repository: the Git repo on a server
Workflow
- Clone the code from a remote repository to a local repository.
- Checkout code from the local repository and modify it.
- Before committing, add changes to the staging area.
- Commit to the local repository, which records each historical version.
- When ready to share with the team, push the changes to the remote repository.
Code Hosting
Git uses both local and remote repositories. To set up a remote repository, you can use online hosting services such as GitHub, Gitee (a Chinese platform), or GitLab.
- GitHub (URL: https://github.com/) – a platform for open‑source and private projects; it only supports Git as the repository format (hence the name).
- Gitee (URL: https://gitee.com/) – a domestic Chinese code‑hosting service; because its servers are in China, it is generally faster than GitHub for users there.
- GitLab (URL: https://about.gitlab.com/) – an open‑source web service for repository management that uses Git as the underlying VCS.
Account and SSH‑Key Configuration
After installing Git, set your user name and email because every Git commit records this information, which is independent of any code‑hosting platform account.
Set personal information:
- User name:
git config --global user.name kengong - Email:
git config --global user.email ken.gong@innos.com
View configuration:
The settings above are stored in the /.gitconfig file in your home directory.
Generate an SSH public key:
Ensure you have an account.
cd ~/.ssh(check whether an SSH key already exists) in the user directory.Generate a new SSH key:
ssh-keygen -t rsa -C "email"-tspecify the key type (default is RSA; can be omitted)-Cadd a comment, e.g., your email-fchoose the filename for the key file
View the key:
cat ~/.ssh/id_rsa.pubTest the public key:
ssh -T git@github.com
Local Repository
Getting a Repository
Initialize a local repository
- Create an empty folder anywhere on your computer (e.g.,
repo1). - Open Git Bash in that folder (right‑click → “Git Bash Here”).
- Run
**git init**. If you see a hidden.gitfolder, the Git repository was created successfully.
Remote repository cloning
Clone a remote repository with Git’s built‑in command: git clone <remote‑url> (HTTPS or SSH).
Working Process
- Repository: the hidden
.gitfolder stores configuration, logs, and version data. - Working directory (working tree): the directory containing the
.gitfolder holds your source code. - Staging area: inside the
.gitfolder there is aindexfile (also called thestage), which temporarily holds the files you have staged.
File Operations
Common Commands
| Command | Description |
|---|---|
git status |
Show the status of files (added, committed, etc.) |
git add <filename> |
Add a specific file to the staging area |
git commit -m 'message' |
Commit staged files to the local repository and clear them from the staging area |
git commit --amend |
Change the commit message |
git rm <filename> |
Delete a file from the working tree (needs to be committed) |
git mv <filename> |
Move or rename a file in the working tree |
git reset <filename> |
Overwrite the staging area with the current branch’s version, unstaging the file |
git checkout <filename> |
Overwrite the working directory with the staged version (dangerous – discards changes) |
git log |
View commit history |
git reflog |
View all actions on all branches, including deleted commits |
| |
Other commands: You can bypass the staging area or commit directly from a branch.
git commit -a– stage all changes and commit them in one step.git checkout HEAD -- files– retrieve the last change, useful for rollback.
File Status
Files in the working directory can be in several states:
untracked – not under version control
tracked – under version control
- Unmodified – unchanged
- Modified – changed but not staged
- Staged – added to the staging area
View file status:
git status– show detailed statusgit status –s– show a concise status
Ignoring Files
Sometimes you have files that should not be tracked (e.g., logs, temporary build files). Create a file named .gitignore in the working directory (the name is fixed) and list patterns for files to ignore.
Example:
Remote Repository
Workflow
Git defines four areas: working directory, staging area, local repository, and remote repository.
pull = fetch + merge
fetch updates the local repository from the remote; pull updates the working directory directly from the remote.
Viewing Remotes
git remote– list all remote aliases (short names)git remote -v– list all remote URLsgit remote show– show detailed info for a specific remote
Adding a Remote
git remote add– add a new remote and give it a short alias
Cloning a Repository
git clone (HTTPS or SSH)– clone a remote repository
Git clones almost all data from the server (logs, history, etc.), not just the files needed for the current checkout. By default, every version of every file is fetched.
Removing a Remote
git remote rm– remove a remote from the local configuration (does not affect the remote server)
Fetching Updates
git fetch– fetch the latest version from the remote to the local repository (no automatic merge)git pull– fetch and merge the latest remote version into the local repository
Note: If your local repository was created locally (not cloned) and already contains files, pulling from a remote will fail with
fatal: refusing to merge unrelated histories. Add the--allow-unrelated-historiesoption togit pullto allow the merge.
Pushing Changes
git push– push a specified local branch to the remote repository
Version Management
Command: git reset --hard – unique version identifier
Branch Management
Listing Branches
git branch– list all local branchesgit branch -r– list all remote branchesgit branch -a– list both local and remote branches
Creating Branches
git branch branch-name– create a new branch but stay on the current branchgit checkout -b branch-name– create a new branch and switch to it
Pushing Branches
git push origin branch-name– push to the remote;originis the remote name
Switching Branches
git checkout branch-name– switch tobranch-name
Merging Branches
git merge branch-name– merge the specified branch into the current branch
If there are conflicting changes to the same part of a file on different branches, Git will report a conflict. Open the conflicted file, resolve the differences, then run git add to mark the conflict as resolved.
Deleting Branches
git branch -d branch-name– delete a local branchgit push origin –d branch-name– delete a remote branch (originis the remote name)
If the branch has unmerged work, the delete command will refuse to remove it. To force deletion, replace the -d flag with -D: git branch -D branch-name.
Tag Management
Listing Tags
git tag– list all tagsgit show tag-name– show detailed information about a tag
Tags are used to mark important points in development (e.g., releases, major changes, upgrades) and permanently record those milestones.
Creating Tags
git tag tag-name– create a tag, e.g.,git tag v1.0.1
Pushing Tags
git push [remotename] [tagname]– push a tag to the remote repositorygit push [remotename] --tags– push all tags
Switching Tags
git checkout tag-name– checkout a tag
Deleting Tags
git tag -d tag-name– delete a local taggit push origin :refs/tags/ tag-name– delete a remote tag
Originally written by Li Wei (李唯_) and published in Chinese on 后端技术栈全书 (Full-Stack Backend Engineering). Translated and adapted for DriftSeas with permission.