Git is an open-source distributed version control system that can effectively and quickly handle version management of projects ranging from small to very large. Here are some commonly used Git commands recorded during personal learning.
1. Repository#
1. Repository#
Initialize repository
git init
Clone repository
git clone username@host:/path/to/repo
2. Workflow#
A local repository consists of three parts: working directory, staging area, and HEAD. The working directory contains the actual files; the staging area temporarily saves changes; the HEAD points to the result after the most recent commit.
The general workflow is as follows:
- Add or modify files in the working directory;
- Put the files that need version management into the staging area;
- Commit the files in the staging area to the Git repository;
Add and commit
git add <filename> // Add a file to the staging area
git commit -m "Commit message" // Commit the file to the local repository HEAD
Push to remote repository
git push origin master // master can be replaced with any branch you want to push to
// If you haven't cloned an existing repository and want to connect to a remote server
git remote add origin <server>
3. Branch#
Create a branch
git checkout -b feature_x
Switch branches
git checkout master
Delete a branch
git branch -d feature_x
4. Update and Merge#
Update local repository
git pull
Fetch/merge branches
git fetch <branch> // Fetch a branch
git merge <branch> // Merge a branch
View changes
git diff <source_branch> <target_branch>
Create tags
git tag 1.0.0 1b2e1d63ff // 1.0.0 is the created tag, 1b2e1d63ff is the first 10 characters of the tagged commit ID, can also be less than 10 characters
git log // Get the commit ID
5. Discard Local Changes#
Replace local changes
git checkout -- <filename> // Replace the working directory file with the latest content in HEAD, the changes in the staging area and new files are not affected, can be used to correct mistakes
Discard local changes
git fetch origin // Get the latest version from the server
git reset --hard origin/master // Point the local branch to the remote server branch