Git
Git
DevOps Shack
Git Simplified: Mastering Version Control
Table of Contents
1. Introduction to Git
o What is Git?
o Why use Git?
o Difference between Git and GitHub
o Basic Git workflow
2. Setting Up Git
o Installing Git on Windows, macOS, and Linux
o Configuring Git (username, email, editor)
o Verifying installation
3. Initializing and Cloning Repositories
o Creating a new Git repository (git init)
o Cloning an existing repository (git clone)
4. Basic Git Commands
o Checking repository status (git status)
o Adding files to staging (git add)
o Committing changes (git commit)
5. Branching and Merging
o Creating branches (git branch, git checkout -b)
o Switching branches (git switch, git checkout)
o Merging branches (git merge)
6. Working with Remote Repositories
2
o Adding a remote repository (git remote add origin)
o Pushing changes (git push)
o Pulling updates (git pull)
7. Undoing and Reverting Changes
o Undoing last commit (git reset --soft, git reset --hard)
o Removing files from staging (git reset)
o Reverting a commit (git revert)
8. Stashing Changes
o Temporarily saving changes (git stash)
o Viewing and applying stashed changes (git stash list, git stash pop)
9. Git Best Practices
o Writing meaningful commit messages
o Keeping commits small and focused
o Using branches for new features
10. Advanced Git Tips & Troubleshooting
Viewing commit history (git log, git reflog)
Fixing merge conflicts
Recovering lost commits
3
1. Introduction to Git
What is Git?
Git is a distributed version control system (VCS) that helps developers track
changes in their code, collaborate efficiently, and manage different versions of
a project. Unlike traditional version control systems, Git allows multiple people
to work on the same codebase without conflicts.
Why Use Git?
Tracks Changes – Keeps a history of all modifications.
Collaboration – Multiple developers can work on the same project.
Branching & Merging – Create separate workspaces without affecting
the main project.
Backup & Recovery – Easy to revert to previous versions.
Works Offline – No need for an internet connection to work locally.
Git vs. GitHub
Git – A tool for version control that runs on your local system.
GitHub – A cloud-based platform that hosts Git repositories for
collaboration and backup.
Basic Git Workflow
A typical Git workflow follows these steps:
1. Initialize a repository – Start tracking a project with git init or clone an
existing one with git clone.
2. Make changes – Modify files in your project.
3. Stage changes – Add updated files to the staging area using git add.
4. Commit changes – Save changes to Git’s history with git commit -m
"message".
5. Push changes – Upload changes to a remote repository (git push).
6. Pull updates – Get the latest updates from a remote repository (git pull).
Key Git Commands for This Section
4
git init # Initialize a new Git repository
git clone <url> # Clone an existing repository
git add <file> # Add a file to the staging area
git commit -m "message" # Commit changes with a message
git push origin main # Push changes to remote repository
git pull origin main # Pull the latest changes from remote
Would you like any additional explanations or examples before moving to the
5
4. Works Offline
o Unlike other version control systems, Git lets you work without an
internet connection.
git init starts tracking your git push sends your project to
Example?
project. GitHub.
Think of Git as your personal notebook where you track changes and GitHub as
a shared online workspace where everyone can access and collaborate.
6
echo "<h1>Hello, Git!</h1>" > index.html
🔹 Expected Output:
Untracked files:
(use "git add <file>..." to include in what will be committed)
index.html
This means Git sees the file but isn’t tracking it yet.
🔹 Expected Output:
[main (root-commit) abc1234] Initial commit: Added index.html
1 file changed, 1 insertion(+)
Now, Git has officially saved this version.
7
To see a list of all saved changes:
git log --oneline
🔹 Expected Output:
abc1234 Initial commit: Added index.html
Each commit has a unique ID (hash) that helps track changes.
Command Description
8
2. Setting Up Git
Before using Git, you need to install and configure it on your system. This
section covers:
✅ Installing Git on different operating systems
✅ Configuring Git with your name and email
✅ Verifying installation
Installing Git
On Windows
1. Download the latest Git for Windows from git-scm.com.
2. Run the installer and follow the default settings.
3. Open Git Bash (installed with Git).
On macOS
Using Homebrew (recommended):
brew install git
Verify installation:
git --version
On Linux
Ubuntu/Debian:
sudo apt update && sudo apt install git
Fedora:
sudo dnf install git
Verify installation:
git --version
Configuring Git
9
After installing Git, configure it with your name and email (required for
commits).
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
🔹 Example:
git config --global user.name "John Doe"
git config --global user.email "john@example.com"
To check your current Git settings:
git config --list
🔹 Expected Output:
user.name=John Doe
user.email=john@example.com
10
git config --global credential.helper cache
This stores your credentials temporarily so you don’t have to enter them every
time.
Command Description
git config --global user.name "Your Name" Sets your Git username.
11
3. Initializing and Cloning Repositories
This section covers:
✅ How to create a new Git repository (git init)
✅ How to clone an existing repository (git clone)
🔹 Expected Output:
Initialized empty Git repository in /path/to/your/project/.git/
This creates a hidden .git folder inside your project, where Git will track
changes.
Step 3: Verify Initialization
To check if Git is tracking the repository:
git status
Since no files are tracked yet, you’ll see:
On branch main
No commits yet
Untracked files:
(use "git add <file>..." to include in what will be committed)
12
Cloning an Existing Repository
Instead of starting from scratch, you can copy an existing project from GitHub
or another Git server using git clone.
Step 1: Find the Repository URL
On GitHub, GitLab, or Bitbucket, go to the project and copy its HTTPS or SSH
URL. Example:
https://github.com/user/repository.git
Step 2: Clone the Repository
Run the following command:
git clone <repository-url>
Example:
git clone https://github.com/user/repository.git
🔹 Expected Output:
Cloning into 'repository'...
remote: Enumerating objects: 100, done.
remote: Counting objects: 100% (100/100), done.
Receiving objects: 100% (100/100), 500 KiB | 1.2 MiB/s, done.
This will create a new folder with the project files inside.
Step 3: Navigate to the Cloned Repository
Move into the cloned folder:
cd repository
Step 4: Check Remote Repository
To confirm that Git is connected to the remote repository:
git remote -v
🔹 Expected Output:
origin https://github.com/user/repository.git (fetch)
13
origin https://github.com/user/repository.git (push)
Command Description
14
4. Understanding Git Staging and Committing
In this section, we’ll cover:
✅ How Git tracks changes (Working Directory → Staging → Commit)
✅ Adding files to staging (git add)
✅ Committing changes (git commit)
✅ Viewing commit history (git log)
🔹 Flow Diagram:
[Working Directory] → git add → [Staging Area] → git commit → [Repository]
Adding Files to Staging
After modifying or creating new files, Git does not automatically track
changes. You need to add them to the staging area.
Step 1: Check the Current Status
git status
15
git add file1.txt file2.txt
Step 4: Add All Files to Staging
git add .
Step 5: Verify Staging Status
git status
🔹 Expected Output:
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
new file: index.html
Committing Changes
A commit permanently saves the staged changes into the repository. Think of it
as a checkpoint in your project.
Step 1: Commit Changes with a Message
git commit -m "Added homepage"
🔹 Expected Output:
[main abc1234] Added homepage
1 file changed, 10 insertions(+)
create mode 100644 index.html
Step 2: Commit All Staged Files in One Command
git commit -a -m "Updated multiple files"
⚠️ This command only works for modified files that were previously
committed. New files still need git add.
🔹 Expected Output:
abc1234 Added homepage
def5678 Fixed navbar issue
Step 2: View Full Commit History
git log
🔹 This will show details like author, date, and commit message.
🔹 The file will move back to the working directory, meaning it's no longer
staged.
Step 2: Remove All Staged Files
git reset
Command Description
git commit -m
Commits staged changes with a message.
"message"
17
Command Description
18
5. Working with Branches in Git
In this section, we’ll cover:
✅ What branches are and why they are useful
✅ Creating and switching branches (git branch, git checkout, git switch)
✅ Merging branches (git merge)
✅ Deleting branches (git branch -d)
🔹 Example Workflow:
(main) ────────┐
├── (feature-branch) ─── New Feature
└── (bugfix-branch) ─── Bug Fix
By default, Git starts with a branch called main or master.
19
git checkout feature-1
Using switch (recommended):
git switch feature-1
🔹 Expected Output:
Switched to branch 'feature-1'
Step 4: Create and Switch in One Command
git checkout -b feature-1
OR
git switch -c feature-1
Merging Branches
Once a feature is complete, merge it into the main branch.
Step 1: Switch to the main Branch
git switch main
Step 2: Merge Another Branch into main
git merge feature-1
20
Automatic merge failed; fix conflicts and then commit the result.
How to Fix a Merge Conflict
1. Open the conflicting file in a text editor.
2. Git marks conflicts like this:
<<<<<<< HEAD
Code from main branch
=======
Code from feature-1 branch
>>>>>>> feature-1
3. Manually edit the file to keep the correct version.
4. Add the resolved file:
git add index.html
5. Commit the merge:
git commit -m "Resolved merge conflict"
Deleting Branches
Step 1: Delete a Local Branch
Once merged, you can delete the branch:
git branch -d feature-1
🔹 If the branch is not merged yet, Git will warn you. To force delete:
git branch -D feature-1
Step 2: Delete a Remote Branch
git push origin --delete feature-1
21
Command Description
22
6. Working with Remote Repositories
In this section, we’ll cover:
✅ Connecting a local repository to a remote repository
✅ Pushing and pulling changes (git push, git pull)
✅ Fetching updates without merging (git fetch)
✅ Working with multiple collaborators
🔹 Replace origin with any name if needed, but origin is the default.
Step 3: Verify the Remote Repository
git remote -v
🔹 Expected Output:
origin https://github.com/user/repository.git (fetch)
origin https://github.com/user/repository.git (push)
23
🔹 The -u flag links your local branch with the remote branch.
Step 2: Push Subsequent Commits
Once the upstream is set, simply use:
git push
🔹 This fetches new commits and merges them into your local branch.
Step 2: Pull Without Merging (Fetch Only)
To see updates without merging:
git fetch origin
24
Step 2: Resolve Conflicts (If Any)
If there are merge conflicts, Git will ask you to resolve them manually.
Steps:
1. Open the conflicting file and edit it.
2. Use git add <file> to stage the resolved file.
3. Commit the changes with git commit -m "Resolved conflict".
4. Push the changes:
git push origin main
Command Description
25
7. Undoing Changes and Reverting Commits
In this section, we’ll cover:
✅ Undoing local changes before committing
✅ Resetting and reverting commits (git reset, git revert)
✅ Checking out previous commits (git checkout <commit-hash>)
✅ Stashing changes (git stash)
⚠️ This command cannot be undone and will restore the file to the last
committed version.
Step 2: Discard Changes in All Files
git checkout -- .
🔹 This removes the file from staging but keeps the changes in the working
directory.
To unstage all files:
git reset
26
If you already committed changes but haven't pushed yet, you can undo the
last commit.
Step 1: Soft Reset (Undo Commit but Keep Changes Staged)
git reset --soft HEAD~1
🔹 This undoes the last commit but keeps your files staged.
Step 2: Mixed Reset (Undo Commit and Unstage Changes)
git reset --mixed HEAD~1
🔹 This undoes the commit and unstages the changes, but keeps them in the
working directory.
Step 3: Hard Reset (Undo Commit and Discard Changes)
git reset --hard HEAD~1
27
git switch main
🔹 This restores the last stashed changes but keeps them in stash.
Step 4: Apply and Remove the Stash
git stash pop
Step 5: Remove All Stashes
git stash clear
Command Description
git reset --soft HEAD~1 Undo last commit but keep files staged.
git reset --mixed HEAD~1 Undo last commit and unstage files.
git reset --hard HEAD~1 Undo commit and delete changes permanently.
28
Command Description
29
8. Git Log, Aliases, and Advanced Tips
In this section, we’ll cover:
✅ Viewing commit history with git log
✅ Using aliases for efficiency
✅ Advanced Git tips for productivity
🔹 Example Output:
a1b2c3d Fix login page bug
e4f5g6h Add user authentication
i7j8k9l Initial commit
This makes it easier to scan through commit history quickly.
View Logs with Graph
git log --oneline --graph --all
30
Show commits by a specific author:
git log --author="John Doe"
Search for a keyword in commit messages:
git log --grep="bugfix"
Show commits within a date range:
git log --since="2024-01-01" --until="2024-03-01"
31
🔹 This displays the last commit's changes.
2. Find Who Changed a Line in a File
git blame filename.txt
🔹 This shows the author and commit hash for each line in a file.
3. Restore a Deleted File
If you accidentally delete a file and haven’t committed yet:
git checkout -- filename.txt
If the file was deleted in a commit:
git checkout HEAD~1 filename.txt
4. Amend the Last Commit
git commit --amend -m "Updated commit message"
🔹 This changes the last commit message without creating a new commit.
5. Clean Untracked Files
If you want to remove untracked files (files not in Git):
git clean -f
Command Description
32
Command Description
git commit --amend -m "<new message>" Edit the last commit message.
33
9. Git Best Practices
In this section, we’ll cover:
✅ Writing clear commit messages
✅ Structuring branches effectively
✅ Avoiding common mistakes
✅ Keeping repositories clean
34
Branch Type Naming Example
35
This keeps the history intact.
36
Best Practice Command/Guideline
Conclusion
Git is an essential tool for developers, enabling efficient collaboration, version
control, and code management. In this guide, we covered:
37