KEMBAR78
Git Commands Cheatsheet & Practical Guide | PDF | Computing | Software
0% found this document useful (0 votes)
27 views15 pages

Git Commands Cheatsheet & Practical Guide

This document serves as a comprehensive guide to mastering Git, detailing essential commands and real-world scenarios for effective version control. It covers topics such as setup, branching, merging, and collaboration, along with best practices for a professional workflow. The guide aims to equip developers of all experience levels with the knowledge to utilize Git effectively in their projects.

Uploaded by

itsme770011
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views15 pages

Git Commands Cheatsheet & Practical Guide

This document serves as a comprehensive guide to mastering Git, detailing essential commands and real-world scenarios for effective version control. It covers topics such as setup, branching, merging, and collaboration, along with best practices for a professional workflow. The guide aims to equip developers of all experience levels with the knowledge to utilize Git effectively in their projects.

Uploaded by

itsme770011
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

🚀

Mastering Git: Your Essential Guide with Real-World


Scenarios
Git is an indispensable tool for every developer, regardless of experience level. It's a
distributed version control system that helps you track changes in your code,
collaborate seamlessly with others, and revert to previous states if something goes
wrong. Think of it as a time machine for your code!

This guide is structured to provide a quick reference for Git commands, followed by
real-world implementation scenarios to solidify your understanding.

1. Git Commands Reference: A Quick Guide 📚


This section provides a consolidated list of essential Git commands, categorized for
easy lookup.

1.1. Basic Setup & Configuration 🛠️


●​ git config --global user.name "Your Name": Sets your name globally for all Git
repositories.

●​ git config --global user.email "your.email@example.com": Sets your email


globally.

●​ git config --list: Shows all your Git configurations.


1.2. Initializing & Working with Changes 🔄
●​ git init: Initializes a new, empty Git repository in your current directory.

●​ git init --initial-branch=main: Initializes a new repository with 'main' as the


default branch name.

●​ git status: Shows the current state of your working directory and staging area
(untracked, modified, or staged files).

●​ git add <file>: Stages a specific file for the next commit.

●​ git add . : Stages all changes in the current directory and its subdirectories.

●​ git commit -m "Your commit message": Records the staged changes into the
local repository with a descriptive message.

●​ git commit -am "Message": Adds and commits tracked files in one step.

●​ git commit --amend: Edits the last commit message or adds new changes to the
previous commit.
1.3. Inspecting History & Differences 📖
●​ git log: Displays the entire commit history.

○​ git log -n<number>: Shows the last n commits.

○​ git log --oneline: Shows a concise history, one commit per line with a
shortened SHA.

○​ git log -p: Shows the full diff (changes) introduced by each commit.

○​ git log --pretty=format:"%h %an %s %ad": Customizes the log output.

●​ git diff: Shows unstaged changes in your working directory.

●​ git diff <file>: Shows changes for a specific file.

●​ git diff <branch1> <branch2>: Compares changes between two branches.

●​ git show <commit-id>: Displays detailed information about a specific commit,


including its changes.

●​ git reflog: Shows a history of all the HEAD movements.


1.4. Undoing Changes ⏳
●​ git reset <file>: Unstages a specific file. Changes remain in your working
directory.

●​ git reset --soft <commit-id>: Undoes commit(s) after specified commit, keeps
changes staged.

●​ git reset --mixed <commit-id> (Default): Undoes commit(s) after specified


commit, keeps changes in working directory but unstaged.

●​ git reset --hard <commit-id>: DANGER! Undoes commit(s) after specified


commit and discards all changes.

●​ git revert <commit-id>: Creates a new commit that undoes the changes
introduced by the specified commit.
1.5. Branching & Merging 🌳
●​ git branch: Lists all local branches.

●​ git branch <branch-name>: Creates a new branch.

●​ git checkout <branch-name> / git switch <branch-name>: Switches to an


existing branch.

●​ git checkout -b <branch-name>: Creates a new branch AND switches to it.

●​ git merge <branch-name>: Integrates changes from the specified branch into
your current branch.

●​ git branch -d <branch-name>: Deletes a local branch (only if fully merged).

●​ git branch -D <branch-name>: Force deletes a local branch.

●​ git rebase <branch-name>: Reapplies commits on top of another base (rewrites


history).

●​ git rebase -i HEAD~<n>: Interactive rebase to edit, squash, reorder, or delete the
last n commits.
1.6. Working with Remote Repositories 🌐
●​ git clone <repo-url>: Downloads an existing remote repository to your local
machine.

●​ git remote add origin <url>: Links your local repository to a remote one.

●​ git remote -v: Lists configured remote repositories.

●​ git remote set-url origin <new-url>: Updates the URL for a remote.

●​ git remote rename <old-name> <new-name>: Renames a remote.

●​ git push -u origin <branch-name>: Pushes local commits to the specified


remote branch and sets upstream tracking.

●​ git push origin :<branch-name>: Deletes a remote branch.

●​ git fetch: Downloads new changes from the remote without integrating them into
local branches.

●​ git pull origin <branch-name>: Fetches changes from the remote and then
merges them into your current local branch (git pull = git fetch + git merge).

●​ git branch -a: Lists all branches, including remote-tracking branches.


1.7. Advanced & Utility Commands ✨
●​ git stash: Temporarily saves unstaged and staged changes, cleaning your
working directory.

●​ git stash list: Shows a list of stashed changes.

●​ git stash pop: Reapplies the most recent stashed changes and removes them.

●​ git stash apply: Reapplies stashed changes without removing them from the list.

●​ git stash clear: Removes all stashed entries.

●​ .gitignore file: Lists patterns for files/directories Git should ignore.

●​ git tag <tag-name>: Adds a lightweight tag to the current commit (e.g., v1.0.0).

●​ git tag -d <tag-name>: Deletes a local tag.

●​ git shortlog -s -n: Summarizes commit activity by author.

●​ git blame <file>: Shows who last modified each line of a file.

●​ git grep "search-term": Searches for a specific term within tracked files.

●​ git clean -f: Removes untracked files from the working directory.

●​ git clean -fd: Removes untracked files and directories.


2. Implementation Scenarios: Putting Git into Practice 💡
This section dives into practical examples, demonstrating how to use Git commands in
real-world development situations.

Scenario 1: First-Time Git Setup 👤


Situation: You've just installed Git on a new machine and want to configure your
identity so that all your future commits are correctly attributed to you.

Implementation:

git config --global user.name "Sangeeta Sharma"​


git config --global user.email "sangeeta.sharma@example.com"​
git config --list # To verify the settings

Scenario 2: Starting a New Project and Making Your First Commit 🏗️


Situation: You're starting a new web project called "MyWebApp" and want to track its
initial files (index.html, style.css, script.js) with Git.

Implementation:
1.​ Create your project directory and navigate into it:​
mkdir MyWebApp​
cd MyWebApp​

2.​ Initialize a new Git repository:​


git init --initial-branch=main​

3.​ Create your initial project files:​


touch index.html style.css script.js​

4.​ Check the status (you'll see untracked files):​


git status​
# Output will show "Untracked files: index.html, style.css, script.js"​

5.​ Stage all new files:​


git add .​
6.​ Check status again (now files are staged):​
git status​
# Output will show "Changes to be committed: new file: index.html, style.css,
script.js"​

7.​ Commit your first changes:​


git commit -m "Initial commit: Set up project structure"​

8.​ Later, if you make a small change and want to add it to the last commit:​
# Make a change to index.html​
git add index.html​
git commit --amend --no-edit # Amends the last commit without changing its
message​
# Or, to change the message as well:​
# git commit --amend -m "Updated initial setup and fixed typo in index.html"

Scenario 3: Investigating Recent Changes 🕵️‍♀️


Situation: You've made several changes and commits. Now you want to review what
you've done, see the history concisely, and check specific differences.

Implementation:
1.​ See a quick summary of recent changes:​
git log --oneline​
# Example Output:​
# abcdef1 Added user authentication module​
# fedcba9 Implemented navbar responsiveness​
# 1234567 Initial commit​

2.​ View the detailed changes of the latest commit:​


git show HEAD # HEAD points to your latest commit​

3.​ See all changes you've made since your last commit (unstaged changes):​
git diff​

4.​ Compare your current branch with another branch (e.g., 'feature-X'):​
git diff main feature-X​

5.​ If you need to find a "lost" commit or see every action that moved HEAD:​
git reflog​

Scenario 4: Correcting Mistakes & Undoing Changes ↩️


Situation A: You staged a file but haven't committed yet, and you want to
unstage it.

Implementation:

git add wrong_file.txt # Accidentally staged​


git status # Shows wrong_file.txt as "Changes to be committed"​
git reset wrong_file.txt # Unstages the file​
git status # wrong_file.txt is now "Untracked" or "Modified"

Situation B: You made a commit, but realize it was a mistake and want to
completely erase it from history (only if it's not pushed to a shared remote!).

Implementation:

git log --oneline # Identify the commit ID you want to undo, e.g., 'abcdef1'​
git reset --hard abcdef1 # This will remove all changes and commits after 'abcdef1'​

●​ Warning: Only use --hard reset on commits that have not been pushed to a
shared remote repository. Rewriting shared history can cause problems for
collaborators.

Situation C: You made a commit, and it has been pushed to a shared remote. You
need to undo its effects but safely, without rewriting history.

Implementation:

git log --oneline # Find the commit ID you want to revert, e.g., '1a2b3c4'​
git revert 1a2b3c4 # Git will create a new commit that undoes the changes of 1a2b3c4​

Scenario 5: Developing a New Feature and Integrating It 🌿


Situation: You need to add a new "user profile" feature without disrupting the stable
main branch.

Implementation:
1.​ Ensure you are on the main branch and it's up to date (we'll cover remotes
later):​
git checkout main​

2.​ Create a new feature branch:​


git checkout -b feature/user-profile​

3.​ Work on your feature: Add files, make changes, commit often on this branch.​
# (Create profile.js, update index.html)​
git add .​
git commit -m "feat: Added basic user profile page"​
# ... more commits ...​

4.​ Once the feature is complete, switch back to main:​


git checkout main​

5.​ Merge your feature branch into main:​


git merge feature/user-profile​

6.​ Resolve Merge Conflicts (if they occur):


○​ If Git can't automatically merge changes (e.g., both branches modified the
same line), it will declare a conflict.
○​ git status will show conflicted files.
○​ Open the conflicted files; you'll see markers like <<<<<<<, =======, >>>>>>>
indicating the conflicting sections.
○​ Manually edit the file to resolve the conflict (choose which changes to keep).
○​ After resolving, git add <conflicted-file> to mark it as resolved.
○​ Finally, git commit -m "Merged feature/user-profile and resolved conflicts" to
complete the merge.
7.​ Delete the feature branch (after successful merge):​
git branch -d feature/user-profile

Scenario 6: Collaborating on a Team Project 🤝


Situation: You're working with a team. You need to get the latest changes from
others, push your own work, and keep your local repository synchronized.

Implementation:
1.​ Clone the existing team repository:​
git clone https://github.com/your-org/team-project.git​
cd team-project​

2.​ Make sure your local main branch is up-to-date with the remote main:​
git checkout main​
git pull origin main # Fetches and merges changes from remote main​

3.​ Create a new feature branch, work, and commit as usual:​


git checkout -b feature/dashboard-improvements​
# (Make changes and commits)​

4.​ Before merging to main (or creating a Pull Request), push your feature
branch to the remote so others can see it:​
git push -u origin feature/dashboard-improvements​

5.​ Later, if a colleague's commit (abcde12) on a different branch (bugfix/typo)


is crucial for your work, but you don't want to merge the entire branch:​
git cherry-pick abcde12 # Applies specific commit from bugfix/typo to your
current branch


Scenario 7: Handling Interruptions & Ignoring Files 🧹
Situation A: You're in the middle of developing a feature, but an urgent bug fix
comes up. You don't want to commit your incomplete feature, but need to switch
branches.

Implementation:
1.​ Stash your current work:​
git stash​
# Your working directory is now clean, ready to switch branches.​

2.​ Switch to the bugfix branch, fix the bug, commit, and push.
3.​ Switch back to your feature branch:​
git checkout feature/your-feature​

4.​ Reapply your stashed changes:​


git stash pop # Applies and removes from stash list​

Situation B: Your project generates temporary files (.log files, node_modules for
Node.js projects) that you don't want Git to track or include in commits.

Implementation:
1.​ Create a file named .gitignore in the root of your project.
2.​ Add patterns for files/folders to ignore:​
# .gitignore content​
*.log # Ignores all files ending with .log​
node_modules/ # Ignores the node_modules directory​
.env # Ignores environment variable files​

3.​ Commit the .gitignore file:​


git add .gitignore​
git commit -m "Add .gitignore to exclude temporary files"​

Now, Git will automatically ignore these files in git status and git add . operations.
3. Git Best Practices for a Professional Workflow 🌟
Beyond commands, adopting best practices is crucial for efficient and collaborative
development.
●​ Commit Often: Make frequent, small commits with descriptive messages. This
creates a granular history, making it easier to revert specific changes if needed.
●​ Branch for Features/Bug Fixes: Always create a new branch for each new
feature, bug fix, or experimental change. This isolates your work and keeps the
main branch stable.
●​ Use Meaningful Commit Messages: Write clear, concise, and descriptive
commit messages. A good message explains what changed and why.
○​ Good Example: feat: Add user registration form with validation
○​ Bad Example: Changes or Fix bug
●​ Pull Regularly: Before starting new work or pushing your changes, always git pull
from the remote main branch. This keeps your local branch updated and
minimizes merge conflicts.
●​ Resolve Conflicts Promptly: Address merge conflicts as soon as they arise. The
longer you wait, the more complex they can become.
●​ Review Pull Requests Thoroughly: For team projects, use Pull Requests (PRs)
(also known as Merge Requests). Thoroughly review PRs to maintain code quality,
share knowledge, and catch potential issues early.
●​ Tag Releases: Use git tag to mark important milestones or releases (e.g., v1.0.0,
v1.1-beta). This provides clear reference points in your project's history.
●​ Keep Your Branches Clean: Delete branches that are no longer needed after
merging them into main. This keeps your repository organized and prevents
clutter.
●​ Squash Commits Before Merging (Optional): For feature branches with many
small, iterative commits, consider using git rebase -i to "squash" related commits
into a single, clean commit before merging. This keeps your main branch history
tidy.
●​ Avoid Large Commits: Keep your commits small and focused on a single logical
change. This makes debugging and understanding history much easier.
●​ Create Descriptive Branch Names: Use naming conventions that describe the
purpose of the branch (e.g., feature/login-form, bugfix/user-auth-issue,
hotfix/critical-api-error).
●​ Keep the Main Branch Deployable: Always ensure that your main (or
production) branch is stable and deployable. It should always represent a working
version of your software.
Conclusion: Your Journey to Git Mastery 🌟
Git is a powerful tool, and mastering it empowers you to be a more efficient and
collaborative developer. By understanding its core concepts and practicing these
commands and best practices, you'll be well-equipped to manage any project's
version control needs.

Remember, practice is key! The more you use Git, the more intuitive it will become.
Happy coding!

You might also like