Welcome to the Git Repository Guide! This repository is designed to provide comprehensive guidance and best practices for using Git effectively. Whether you're a beginner or an experienced developer, you'll find useful information to enhance your Git skills.
Git is a powerful version control system used to manage code changes across projects of all sizes. This repository aims to provide clear and concise information to help you navigate and master Git.
To get started with Git, follow these steps:
- Install Git: Git Downloads
- Configure Git:
git config --global user.name "Your Name" git config --global user.email "your.email@example.com"
- Initialize a repository:
git init
Here are some fundamental Git commands:
git clone <repository-url>: Clone an existing repositorygit add <file>: Add files to staging areagit commit -m "commit message": Commit changesgit push: Push changes to the remote repositorygit pull: Fetch and merge changes from the remote repository
Learn how to manage branches and merge changes:
- Create a new branch:
git checkout -b <branch-name> - Switch branches:
git checkout <branch-name> - Merge branches:
git merge <branch-name>
Explore advanced Git techniques:
- Rebase:
git rebase <branch-name> - Stash changes:
git stash - Cherry-pick:
git cherry-pick <commit-hash>
Follow these best practices to ensure smooth collaboration:
- Commit frequently with meaningful messages
- Keep branches small and focused
- Use pull requests for code reviews
We welcome contributions from the community! If you have a question or improvement that you think should be included, please follow these steps:
- Fork the repository.
- Create a new branch for your contribution.
- Add your question or improvement in the appropriate category folder (
easy,medium,hard). - Submit a pull request with a detailed description of your changes.
Happy coding! If you find this repository helpful, please give it a star ⭐ and share it with others.
Git is a distributed version control system designed to handle everything from small to very large projects with speed and efficiency. It allows multiple people to collaborate on a project, track changes, and revert to previous versions if needed.
To initialize a new Git repository, navigate to your project directory and use the following command:
git initThis command creates a new .git subdirectory in your project directory, which contains all the necessary metadata for the repository.
To clone an existing repository, use the following command:
git clone <repository_url>For example:
git clone https://github.com/user/repository.gitThis command creates a new directory with the name of the repository and copies all the repository data into it.
To check the status of your working directory, use:
git statusThis command shows which files have been modified, which files are staged for commit, and which files are not being tracked by Git.
To stage a file for commit, use:
git add <file_name>For example:
git add README.mdYou can also stage all modified files at once using:
git add .To commit changes, use:
git commit -m "Your commit message"For example:
git commit -m "Add initial project files"The -m flag allows you to add a commit message directly from the command line.
To view the commit history, use:
git logThis command lists all the commits along with their messages, authors, and timestamps.
To create a new branch, use:
git branch <branch_name>For example:
git branch feature-xyzTo switch to an existing branch, use:
git checkout <branch_name>For example:
git checkout feature-xyzTo merge a branch into the current branch, use:
git merge <branch_name>For example, if you are on the main branch and want to merge feature-xyz:
git merge feature-xyzgit pullfetches changes from a remote repository and merges them into your current branch.git fetchonly downloads changes from a remote repository but does not merge them into your current branch.
Example:
git fetch origin
git merge origin/mainis equivalent to:
git pull origin mainTo delete a branch locally, use:
git branch -d <branch_name>For example:
git branch -d feature-xyzTo delete a branch remotely, use:
git push origin --delete <branch_name>For example:
git push origin --delete feature-xyzTo undo the last commit, use:
git revert HEADOr, if you want to remove the commit and the changes:
git reset --hard HEAD~1To discard changes in a file, use:
git checkout -- <file_name>For example:
git checkout -- README.mdTo list all branches, use:
git branchTo create a new tag, use:
git tag <tag_name>For example:
git tag v1.0To push changes, use:
git push <remote> <branch>For example:
git push origin mainTo pull changes, use:
git pull <remote> <branch>For example:
git pull origin mainTo set your Git username and email, use:
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"A commit message is a brief description of the changes made in a commit. It is important because it provides context and reasoning for the changes, making it easier for others (and yourself) to understand the history and purpose of changes in the project.
To view changes made to a file, use:
git diff <file_name>For example:
git diff README.mdTo rename a branch, use:
git branch -m <old_name> <new_name>For example:
git branch -m old-branch-name new-branch-nameTo move or rename a file, use:
git mv <old_path> <new_path>For example:
git mv old_file.txt new_file.txtgit resetmoves the current branch pointer to a specified commit and can also modify the staging area and working directory.git revertcreates a new commit that undoes the changes of a specified commit, preserving the commit history.
Example of git reset:
git reset --hard HEAD~1Example of git revert:
git revert HEAD| Command | Description |
|---|---|
git init |
Initialize a new Git repository |
git clone <repository_url> |
Clone an existing repository |
git status |
Check the status of the working directory |
git add <file_name> |
Stage a file for commit |
git commit -m "message" |
Commit changes to the repository |
git log |
View the commit history |
git branch <branch_name> |
Create a new branch |
git checkout <branch_name> |
Switch to an existing branch |
git merge <branch_name> |
Merge a branch into the current branch |
git pull |
Fetch and merge changes from a remote repository |
git fetch |
Fetch changes from a remote repository |
git branch -d <branch_name> |
Delete a branch locally |
git push origin --delete <branch_name> |
Delete a branch remotely |
git revert HEAD |
Undo the last commit |
git checkout -- <file_name> |
Discard changes in a file |
git branch |
List all branches |
git tag <tag_name> |
Create a new tag |
git push <remote> <branch> |
Push changes to a remote repository |
git pull <remote> <branch> |
Pull changes from a remote repository |
git config --global user.name "name" |
Set Git username |
git config --global user.email "email" |
Set Git email |
git diff <file_name> |
View changes made to a file |
git branch -m <old_name> <new_name> |
Rename a branch |
git mv <old_path> <new_path> |
Move or rename a file |
git reset |
Move the current branch pointer |
git revert |
Create a new commit that undoes changes |
This comprehensive guide should provide you with a solid understanding of Git commands and their usage.
A Git repository is a storage space where your project files and their history of changes are stored. It includes all the project’s files and the entire history of changes made to those files, which allows you to track versions, revert to previous states, and collaborate with others.
- Local Repository: A repository stored on your local machine. You interact with this repository using Git commands.
- Remote Repository: A repository hosted on a remote server. It is often used for collaboration where multiple users push and pull changes.
For example, you clone a remote repository to create a local copy on your machine.
A commit hash is a unique identifier for a specific commit in the Git history. It's a 40-character SHA-1 hash that ensures each commit can be uniquely identified.
Example of a commit hash:
e1a1d3e8b8e3a1b5a1f3c1c8d8e8d8c8c8c8d8d8
To resolve merge conflicts:
- Identify the files with conflicts using
git status. - Open the conflicting files and manually resolve conflicts.
- Stage the resolved files using
git add <file_name>. - Commit the resolved changes using
git commit.
Example:
git add resolved_file.txt
git commit -m "Resolve merge conflict in resolved_file.txt"-
git merge: Combines the changes from one branch into another, creating a merge commit.git merge feature-branch
-
git rebase: Moves or combines a sequence of commits to a new base commit. It creates a linear history.git rebase main
To stash changes, use:
git stashThis command saves your local modifications away and reverts the working directory to match the HEAD commit.
To apply stashed changes, use:
git stash applyOr to both apply and remove the stash:
git stash popThe .gitignore file specifies which files and directories Git should ignore and not track. It helps prevent committing unnecessary files like temporary files, build artifacts, and sensitive information.
Example .gitignore:
*.log
node_modules/
.env
To revert a pushed commit, use:
git revert <commit_hash>This creates a new commit that undoes the changes of the specified commit.
To cherry-pick a commit, use:
git cherry-pick <commit_hash>This command copies the changes from the specified commit and applies them to your current branch.
-
git diff: Shows the changes between commits, branches, files, etc.git diff
-
git log: Shows the commit history.git log
To create a new branch and push it to the remote repository:
git checkout -b <branch_name> && git push -u origin <branch_name>git bisect helps you find the commit that introduced a bug by performing a binary search through your commit history.
Example usage:
git bisect start
git bisect bad
git bisect good <commit_hash>Mark each commit as good or bad until you find the problematic commit.
To squash commits, use interactive rebase:
git rebase -i HEAD~nReplace pick with squash (or s) for the commits you want to squash, then save and close the editor.
To create a bare repository, use:
git init --bare <repository_name>.gitA bare repository is typically used as a central repository for collaboration.
A detached HEAD state occurs when your HEAD is pointing to a commit instead of a branch. This means you are not on any branch.
Example:
git checkout <commit_hash>To configure a remote upstream branch, use:
git branch --set-upstream-to=<remote>/<branch>For example:
git branch --set-upstream-to=origin/mainCreate a file in the .git/hooks directory with the appropriate hook name (e.g., pre-commit, post-commit). Write your script in this file.
Example pre-commit hook:
#!/bin/sh
echo "Running pre-commit hook"Make the script executable:
chmod +x .git/hooks/pre-commitTo force push, use:
git push --forceSubmodules allow you to keep a Git repository as a subdirectory of another Git repository. This is useful for managing dependencies.
Adding a submodule:
git submodule add <repository_url> <path>To clone a repository with submodules:
git clone --recurse-submodules <repository_url>-
--soft: Moves HEAD to the specified commit, but leaves the staging area and working directory unchanged.git reset --soft HEAD~1
-
--mixed(default): Moves HEAD to the specified commit and resets the staging area, but leaves the working directory unchanged.git reset --mixed HEAD~1
-
--hard: Moves HEAD to the specified commit and resets both the staging area and working directory.git reset --hard HEAD~1
To find a specific commit, use:
git log --grep="<search_term>"To change the last commit message, use:
git commit --amend -m "New commit message"-
Annotated Tag: Stores extra metadata such as the tagger name, email, date, and a tagging message. It's stored as a full object in the Git database.
git tag -a <tag_name> -m "Tag message"
-
Lightweight Tag: A simple pointer to a specific commit. It does not store any extra metadata.
git tag <tag_name>
| Command | Description |
|---|---|
git init |
Initialize a Git repository |
git clone <repository_url> |
Clone a repository |
git commit -m "message" |
Commit changes |
git status |
Check the status of the working directory |
git add <file_name> |
Stage changes |
git log |
View commit history |
git diff |
View changes |
git branch <branch_name> |
Create a new branch |
git checkout <branch_name> |
Switch branches |
git merge <branch_name> |
Merge branches |
git rebase <branch_name> |
Rebase branches |
git stash |
Stash changes |
git stash apply |
Apply stashed changes |
git revert <commit_hash> |
Revert a commit |
git cherry-pick <commit_hash> |
Cherry-pick a commit |
git bisect |
Perform binary search to find a commit |
git rebase -i HEAD~n |
Squash commits |
git init --bare |
Create a bare repository |
git branch --set-upstream-to=<remote>/<branch> |
Set upstream branch |
git push --force |
Force push to a remote repository |
git submodule add <repository_url> |
Add a submodule |
git clone --recurse-submodules <repository_url> |
Clone repository with submodules |
git reset --soft |
Reset with soft option |
git reset --mixed |
Reset with mixed option |
git reset --hard |
Reset with hard option |
git log --grep="<search_term>" |
Search commit history |
git commit --amend -m "New message" |
Amend last commit message |
git tag -a <tag_name> -m "message" |
Create an annotated tag |
git tag <tag_name> |
Create a lightweight tag |
This guide should provide a comprehensive understanding of advanced Git commands and concepts.
Git Rebasing is the process of moving or combining a sequence of commits to a new base commit. It allows you to maintain a linear project history.
- Clean History: Rebasing results in a cleaner, more linear commit history.
- Easier Merging: Reduces the complexity of the merge process by avoiding merge commits.
- History Rewriting: Can be dangerous if not used carefully, especially with shared branches, as it rewrites commit history.
- Loss of Context: Merge commits provide a context of when branches were combined, which is lost with rebasing.
Example:
git checkout feature-branch
git rebase mainInteractive rebase allows you to edit, reorder, squash, or drop commits.
Example:
git rebase -i HEAD~3This command opens an editor where you can specify actions for the last three commits.
pick 1234567 Commit message 1
squash 89abcdef Commit message 2
pick fedcba9 Commit message 33. How do you handle a situation where you accidentally pushed sensitive information to a public repository?
- Remove the sensitive data from history:
git filter-branch --force --index-filter \
'git rm --cached --ignore-unmatch <file_path>' \
--prune-empty --tag-name-filter cat -- --all- Force-push the changes:
git push origin --force --all- Invalidate old references:
git push origin --force --tags- Inform collaborators: Notify all collaborators to re-clone the repository.
- Garbage Collection: Run
git gcto optimize the repository by compressing file history. - Pack Files: Use
git repackto create more efficient pack files. - Prune Unreachable Objects: Remove unreachable objects with
git prune.
Example:
git gc --aggressive --prune=nowA Git repository consists of several components:
- Objects: Blobs, Trees, Commits, and Tags.
- Refs: Branches and Tags.
- Index: The staging area.
- HEAD: A pointer to the current branch.
Example:
.git/
├── objects/
├── refs/
├── index
└── HEADUse Git LFS (Large File Storage) to manage large binary files.
Example:
- Install Git LFS:
git lfs install- Track large files:
git lfs track "*.bin"- Add and commit:
git add .gitattributes
git add largefile.bin
git commit -m "Add large file using LFS"
git pushgit fsck checks the integrity of the Git repository, identifying any corrupted objects.
Example:
git fsckUse git filter-branch to rewrite history and remove unwanted data.
Example:
git filter-branch --prune-empty --tree-filter 'rm -rf unnecessary_directory' -- --all- Blobs: Store file data.
- Trees: Represent directories and contain pointers to blobs and other trees.
- Commits: Hold metadata and pointers to tree objects and parent commits.
- Tags: Annotated tags provide metadata for a specific commit.
- Check repository:
git fsck- Recover lost commits:
git reflog- Restore from backup: If available, restore from a backup.
Example using SSH:
- Initialize a bare repository:
git init --bare /path/to/repo.git-
Set up SSH access: Ensure SSH is configured on the server.
-
Push to the remote repository:
git remote add origin user@server:/path/to/repo.git
git push -u origin main-
git archive: Creates a tar or zip archive of the repository.git archive --format=tar HEAD | gzip > repository.tar.gz
-
git bundle: Creates a single file containing the repository data.git bundle create repository.bundle main
Use submodules or monorepos:
Submodules Example:
git submodule add <repository_url> <path>Use git log with the directory path:
git log -- <directory_path>reflog records changes to the tips of branches and other references, allowing you to recover lost commits.
Example:
git reflog- Start bisect:
git bisect start- Mark the bad commit:
git bisect bad- Mark a good commit:
git bisect good <commit_hash>- Continue until the problematic commit is found.
Set the merge tool in your Git configuration:
git config --global merge.tool <tool_name>
git config --global mergetool.<tool_name>.path <path_to_tool>Rewriting history to remove a file:
git filter-branch --index-filter 'git rm --cached --ignore-unmatch <file_path>' -- --all- Overwriting Changes: You might overwrite others' changes.
- History Rewriting: Force-push rewrites history, which can lead to inconsistencies.
- Use SSH keys for authentication.
- Use credential helpers to securely store credentials.
Example:
git config --global credential.helper cacheA Git worktree allows you to have multiple working directories attached to a single repository.
Example:
git worktree add <path> <branch>Use a commit-msg hook:
- Create the hook:
echo -e '#!/bin/sh\nexec <script_path>' > .git/hooks/commit-msg
chmod +x .git/hooks/commit-msg- Write the script to enforce guidelines.
Use git blame with the file path:
git blame <file_path>-
Shallow Cloning: Clones the repository with limited history, reducing download size.
git clone --depth=1 <repository_url>
-
Full Clone: Clones the entire repository history.
25. How do you handle a situation where a merge introduces a bug that needs to be fixed without reverting the merge?
- Identify the bug and create a new branch:
git checkout -b fix-branch- Make necessary changes and commit:
git commit -m "Fix bug introduced in merge"- Merge the fix branch back:
git checkout main
git merge fix-branch| Command | Description |
|---|---|
git rebase -i |
Perform an interactive rebase |
git filter-branch |
Rewrite history |
git fsck |
Check repository integrity |
git gc |
Optimize repository |
git lfs |
Manage large files |
git reflog |
Record changes to refs |
git bisect |
Find a commit introducing a bug |
git worktree |
Manage multiple worktrees |
git blame |
Find the author of a line |
git clone --depth=1 |
Shallow clone repository |
This guide provides an in-depth understanding of advanced Git concepts and commands with examples.