Git is a distributed version control system primarily used for tracking and managing changes to source code. It allows multiple developers to work on code simultaneously and provides powerful tools for merging and managing different versions of code. Below are the basic concepts and usage of Git.
Basic Concepts
- Vertion Control System (VCS): Records changes to files over time so that specific versions can be recalled later. Git is a distributed VCS.
- Repository: Stores project files and their change history. It can be local (on your computer) or remote (e.g., on GitHub).
- Working Directory: The directory containing the project files you are currently editing.
- Staging Area: A temporary area to hold chenges before committing them to the repository.
- Commit: An operation that records changes from the staging area into the repository. Each commit generates a unique hash (SHA-1).
- Branch: An independent line of development. Different branches allow parallel work on different features.
- Merge: Combines changes from different branches into one branch.
- Clone: Copies the entire remote repository to your local machine.
- Pull: Fetches the latest changes from a remote repository and merges them into your local repository.
- Push: Uploads local repository changes to a remote repository.
Basic Usage
Install Git
Download and install Git from the Git official website.
Configure Git
After installation, configure your identity:
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
Create a New Git Repository
Initialize a Git repository in an existing project:
cd your_project_directory
git init
Clone a Remote Repository
Clone a project from a remote repository:
git clone https://github.com/username/repository.git
Check Status
Check the status of your working directory:
git status
Stage Changes
Add files to the staging area:
git add filename
# Or add all changed files
git add .
Commit Changes
Commit staged changes to the repository:
git commit -m "Your commit message"
View Commit History
View the commit history:
git log
Create a Branch
Create a new branch:
git branch new-branch
Switch to the new branch:
git checkout new-branch
Merge Branches
Merge a branch into the current branch:
git checkout main
git merge new-branch
Push Changes to Remote
Push local changes to a remote repository:
git push origin branch-name
Pull Changes from Remote
Fetch and merge the latest changes from a remote repository:
git pull origin branch-name
Common Workflow
- Clone the remote repository: Obtain the project from a remote repository.
- Create a branch: Create a new branch for development.
- Develop: Make code changes on the new branch.
- Commit changes: Commit modifications to your local repository.
- Push changes: Push the local branch to the remote repository.
- Create a pull request: After code review, merge the branch into the main branch.