Course Learning Objectives
Upon completion of this course, students will be able to:
- CLO1 -- Grasp the core concepts and workflows of version control systems like Git .
- CLO2 -- Use Git commands to handle code repositories, including staging, committing, branching, and merging .
- CLO3 -- Work with remote repositories by cloning, pushing, pulling, and rebasing .
- CLO4 -- Apply tools like tagging, stashing, and cherry-picking for advanced tasks .
- CLO5 -- Review and adjust Git history for debugging, auditing, or undoing changes .
Lab Instructions / Rules
- Attendance is mandatory. Internal assessment and record marks are awarded in accordance with the college attendance policy.
- Bring your observation record for every lab session. Record your assigned system number and maintain your GitHub username securely.
- Save your work frequently and maintain backups in a folder named using your USN.
- Write clean, well-structured, and properly documented code. Add code comments when required
- Use a test repository to experiment with Git commands before applying changes to your assignment repository.
- Write meaningful commit messages, use feature branches whenever appropriate, and always fetch/pull the latest changes before pushing to a shared repository.
- Do not modify system settings, install unauthorized software, or access another student's files or GitHub account.
- Complete the assigned experiment during the scheduled lab session and submit the required files before the deadline.
What is Git?
Git is a distributed version control system created by Linus Torvalds in 2005. It tracks source code changes, allowing multiple developers to easily collaborate and maintain a history of edits .
Key Concepts
- Repository -- A directory holding project files and version history .
- Commits -- Snapshots of the project at a specific time .
- Branches -- Independent lines of work for new features or bug fixes .
- Merging -- Combining edits from different branches together .
- Remote Repositories -- Network-hosted project copies (e.g., GitHub, GitLab)[cite: 1].
- Cloning -- Downloading a remote repository to your local machine .
Why Do We Need Git?
- Version Control -- Keep a full history of all file changes .
- Collaboration -- Multiple people can work together without overriding each other's code .
- Branching -- Safely experiment or build features without breaking the main project .
- Distributed System -- Every user has a full project backup locally .
- Efficiency -- Git is fast because it only saves the actual changes made to files, not entire copies .
What is a Version Control System (VCS)?
A VCS tracks and manages file changes over time. It allows developers to collaborate while protecting the integrity of the codebase .
Main Types
- ▹ Centralized VCS -- Uses a single central server (e.g., SVN) .
- ▹ Distributed VCS -- Every user holds a complete copy of the repository (e.g., Git) .
The Git Lifecycle
The standard process for tracking code and collaborating :
- Initialize -- Start tracking a folder using git init .
- Working Directory -- Where you actively edit files .
- Staging -- Selecting files for the next commit using git add .
- Committing -- Saving a snapshot to the local repo using git commit .
- Branching & Merging -- Creating isolated work paths and later combining them[cite: 1].
- Push & Pull -- Syncing your local changes with a remote repository .
Configuration & Installation
Before using Git, you must install the latest stable version of Git for Windows. Git is a distributed version control system that helps you track changes in your source code, collaborate with others, and maintain a complete history of your projects.
Step 1: Download Visual Studio Code and git
Download the latest Visual Studio Code installer from the official website.
Download Visual Studio Code for WindowsDownload the latest 64-bit installer from the official Git website. Always download Git from the official source to ensure you receive the latest stable and secure release.
Download Git for Windows (Latest Stable Release)Step 2: Install Git
Run the downloaded installer and proceed through the installation wizard. Unless instructed otherwise by your instructor, the default installation settings are suitable for almost all users.
Recommended Installation Options
- ✔ Accept the license agreement.
- ✔ Install Git in the default location.
- ✔ Keep the default components selected.
- ✔ Choose Visual Studio Code as the default editor (if installed).
- ✔ Select Git from the command line and also from third-party software.
- ✔ Use the bundled OpenSSH.
- ✔ Use the bundled OpenSSL library.
- ✔ Checkout Windows-style, commit Unix-style line endings (recommended).
- ✔ Use MinTTY as the terminal (default).
- ✔ Enable Git Credential Manager.
- ✔ Enable file system caching.
- ✔ Click Install and wait for the installation to complete.
Step 3: Verify the Installation
After installation, open Command Prompt, PowerShell, Git Bash, or the integrated terminal in Visual Studio Code, and execute the following command:
git --version
If Git has been installed successfully, you should see output similar to:
git version 2.55.0.windows.1
Step 4: Configure Your Git Identity
Every Git commit records information about the author. Before creating your first repository, configure your global username and email address. These details become part of your commit history.
git config --global user.name "Your Full Name"
git config --global user.email "your.email@example.com"
Replace the values above with your own name and the email address associated with your GitHub account. Using the same email address as your GitHub account allows GitHub to correctly associate your commits with your profile.
Step 5: Verify Your Configuration
Confirm that your Git identity has been configured correctly by running:
git config --global user.name
git config --global user.email
Alternatively, display all global configuration settings using:
git config --global --list
- Using a different email address from your GitHub account.
- Typing user.name or user.email incorrectly.
- Forgetting to include quotation marks around names containing spaces.
- Not verifying the installation before proceeding with the lab exercises.
Common Git Commands
A quick reference list of widely used Git commands for tracking changes in software development projects :
- git init -- Initializes a new Git repository .
- git clone <url> -- Copies a remote repository to your local machine .
- git add <file> -- Stages a file for the next commit .
- git commit -m "msg" -- Saves staged changes with a descriptive message .
- git status -- Shows the status of your working directory and staged files .
- git log -- Displays a history of all previous commits[cite: 1].
- git diff -- Shows differences between the working directory and the last commit .
- git branch -- Lists all branches and highlights the current one .
- git branch <name> -- Creates a new branch .
- git checkout <branch> -- Switches to a different branch .
- git merge <branch> -- Merges a specified branch into your current one .
- git pull -- Fetches and merges changes from a remote repository .
- git push -- Uploads local commits to a remote repository[cite: 1].
- git remote -- Lists connected remote repositories .
- git fetch -- Retrieves remote changes without merging them .
- git reset <file> -- Unstages a file .
- git reset --hard <commit> -- Discards all changes and resets to a specific commit .
- git stash -- Temporarily saves uncommitted changes .
- git tag -- Lists and manages release tags .
- git blame <file> -- Shows who changed each line in a file and when .
- git rm <file> -- Deletes a file from the working directory and repository .
- git mv <old> <new> -- Renames a file and stages the change .
Experiment 1. Setting Up, Basic Commands, and Pushing to Remote
Task: Initialize a new Git repository in a directory. Create a new file, add it to the staging area, commit the changes with an appropriate commit message, and push it to a remote repository.
Solution Steps:
Understanding the process: Think of Git as a camera for your project. First, you turn the camera on (init). Then, you create your work (a file). Next, you put your work on a stage to get ready for the picture (add). You take the actual picture and label it (commit). Finally, you upload your picture album to the internet so it is safely backed up and others can see it (remote add and push).
- Open your terminal (or Git Bash) and navigate to the directory (folder) where you want to start your project.
- first make a folder: This command creates an empty folder
mkdir lab1 - get inside the new folder: This command cd stands for change directory
cd lab1 - Initialize the repository: This command creates a hidden folder called .git inside your current directory. This hidden folder is what turns
a normal, everyday folder into a Git repository that can track changes.
git init -
Create a new file: Instead of opening a text editor, you can create a file directly
from your terminal. The echo command prints text, and the > symbol pushes that text into a new file called my_file.txt.
Example programs and snippets
or use the below command to create a file using command prompt
echo "This is my very first Git experiment." > my_file.txt - Add the file to the staging area: Git doesn't track files automatically. The add command tells Git to place this specific file into the "staging
area," which is like a waiting room before the final save.
git add my_file.txt - Commit the changes: The commit command takes a
permanent snapshot of everything in the staging area. The -m flag
stands for "message". You must always wrap your descriptive
message in double quotes. This message acts as a historical record.
git commit -m "Add a new file called my_file.txt" - Connect to a Remote Cloud (GitHub): Before you can upload, you need to tell your
local Git where to send the files. First, create an empty repository on GitHub to get a URL.
Then, use the remote add command. We usually name this connection origin.
📸 Click here to see where to create a new repository on GitHub
git remote add origin https://github.com/yourusername/your-repo-name.gitReplace the URL above with the actual link from your GitHub account.
- Push (Upload) your code: The push command uploads
your local snapshots to the remote cloud server. The -u
flag links your local branch to the remote branch so next time you can just type git push.
git push -u origin mainNote: If your default branch is "master", use git push -u origin master instead.
Experiment 2. Creating and Managing Branches
Task: Set up a new workspace for Lab 2, initialize a Git repository, create a new branch named "feature-branch", add some work, switch back to the main branch, and merge the feature branch.
Solution Steps:
Understanding the process: Branches allow you to create an isolated workspace. Imagine writing a rough draft of an essay on a separate piece of paper. Once you are sure it is perfect, you copy it onto your final, main document. That copying process is called "merging".
master instead of main after
initializing your repository, simply replace the word main with master in all
the commands below.
Git Bash, and
press Enter.
- Create a new folder for Lab 2:
mkdir lab2 - Navigate into the new folder:
cd lab2 - Initialize the repository: Turn this new folder into a Git repository.
git init - Make an initial commit: (Crucial step!) Git will not let you create new
branches until your main branch has at least one snapshot. Let's create a starting file and commit
it.
the below command is to create a new fileecho "Starting point for lab 2" > initial.txt
the below line is to add all the files for staginggit add .
below command is for saving the chanes madegit commit -m "Initial commit on main branch" - Create and switch to a new branch: Using the -b
flag tells Git to do two things at once: First, create a new branch named "feature-branch", and
second, immediately switch your active workspace to it.
git checkout -b feature-branch - Make changes, stage, and commit on the feature branch: Create a new file to
represent your new feature.
Example programs and snippets
echo "Building a new feature." > new_feature.txtgit add .git commit -m "Added new feature on feature-branch" - Switch back to the main workspace: Now that your feature is saved safely on its own
branch, travel back to the main timeline.
git checkout main - Merge the changes: The merge command reaches out
to the "feature-branch", grabs all the completed work you just did, and seamlessly combines it into
your current "main" branch.
git merge feature-branch - (Optional) Connect and Push to Remote: If you want to push this to GitHub, add your
remote origin and push.
git remote add origin https://github.com/yourusername/your-repo-name.git
git push -u origin main
Experiment 3. Creating and Managing Branches (Stashing)
Task: Set up a new workspace for Lab 3, initialize a Git repository, create some unfinished work, stash the changes, switch to a different branch, and then return to apply the stashed changes.
Solution Steps:
Understanding the process: Sometimes you are halfway through writing code, but you suddenly need to switch to another branch to fix an urgent bug. Because your code is unfinished, you shouldn't "commit" it yet. stash acts like a temporary clipboard. It sweeps your messy desk clean so you can switch branches, and lets you bring the mess back later when you are ready to finish.
- Create and enter a new folder for Lab 3:
mkdir lab3
cd lab3 - Initialize and make a base commit: Remember, you need at least one commit before
you can create other branches to switch to!
git init
echo "Base project file" > project.txt
git add .
git commit -m "Initial commit" - Create a second branch (for later): We will create a "bug-fix" branch but stay on
our current main branch for now.
git branch bug-fix - Start some messy work (Do NOT commit): Add some new unfinished text to a file.
echo "Half-written code..." > unfinished.txt
git add .If you try to
git checkout bug-fixright now with uncommitted changes, Git might block you or carry the messy file over to the other branch! - Stash your current changes: This command takes your uncommitted modifications and
hides them away in temporary storage, leaving you with a clean working directory.
git stash save "Working on unfinished text" - Switch to the desired branch safely: Now that your workspace is clean, it is safe
to travel to the other branch.
git checkout bug-fixYou can do your bug fixes here. Let's pretend you finished them and are ready to go back.
- Switch back to your original branch: Let's go back to finish our half-written work.
git checkout main - check the saved stash: you can also get a list of all the stashes
git stash list - Apply the stashed changes: The pop command unpacks
the temporary clipboard, restores your half-finished work exactly as you left it, and deletes it
from the stash clipboard.
git stash pop
apply vs pop: git stash
pop restores the files AND deletes the stash from memory. git stash
apply restores the files but KEEPS a backup in the stash memory just in case. You can view
all saved stashes anytime by typing git stash list.
Experiment 4. Collaboration and Remote Repositories
Task: Clone a remote Git repository to your local machine.
Solution Steps:
Understanding the process: "Cloning" means downloading an exact, full copy of a project from a cloud server (like GitHub) onto your personal computer. It brings down every file, and every single historical snapshot ever taken.
- Open your terminal or command prompt.
- Navigate to your desired folder: Use the cd
(change directory) command to enter the folder where you want this project to live on your hard
drive.
mkdir lab4cd lab4 - Clone the repository: Type git clone followed by
the web address (URL) of the project. This command automatically creates a new folder,
downloads everything, and connects your local folder to the remote cloud server.
git clone https://github.com/Pruthviraj-Guddu/Web-Demon-Slayer-Card.git - Wait for Git to clone the repository to your local machine. Once complete, you will have a local copy in your chosen directory.
- To verify it worked: note that the repository you are trying to clone shoud be
either public or you should have permission to clone it
list out all the files
cd Web-Demon-Slayer-Carddir
Experiment 5. Collaboration and Remote Repositories (Fetch & Rebase)
Collaboration and Remote Repositories: Fetch the latest changes from a remote repository and rebase your local branch onto the updated remote branch
Task: Set up a new workspace for Lab 5, initialize Git, commit, and push. Simulate teamwork by making changes online via GitHub, make a separate local change, fetch the updates, and rebase your local branch onto the updated remote branch.
Solution Steps:
Understanding the process: When working with a team, someone else might upload code to the online repository while you are working on your own code locally. git fetch securely downloads their new code to your computer but doesn't mix it into your files yet. git rebase then takes your un-pushed local work, sets it aside, fast-forwards your folder to match the new online code, and gracefully replays your work perfectly on top. This keeps the project's history in a straight, clean line.
Git Bash, and
press Enter.
- Create a new folder for Lab 5:
mkdir lab5 - Navigate into the new folder:
cd lab5 - Initialize the repository: Turn this folder into a Git repository.
git init - Make the foundational commit: Let's create a starting file so we have a base
history to work with.
echo "Base setup for collaboration" > base_file.txtgit add .git commit -m "Initial commit for lab 5" - Connect and Push to GitHub: Create a new empty repository on GitHub. Link it and
push your code.
git remote add origin https://github.com/yourusername/your-repo-name.gitReplace the URL above with your actual GitHub repository link.
git push -u origin main - Simulate Team Collaboration (Make Changes Online):
Leave your terminal for a moment and open your repository on the GitHub website.
- Click the Add file button, then select Create new file.
- Name the file
online_update.txtand type some text into it. - Click the green Commit changes... button at the top right to save it directly to the main branch.
(Your cloud repository is now one step ahead of your local computer!)📸 Click here to see steps
- Make a Divergent Local Change: Back in your terminal, create a completely different
file. We are simulating that you were working locally while your "teammate" updated the cloud.
echo "My local offline work" > local_work.txtgit add .git commit -m "Added my local work" -
try pusing the code: The push will fail because your local commit history is different from the remote repository's history.
git push origin main - Fetch the latest remote changes: This command securely downloads the information
about
online_update.txtfrom GitHub, but does not alter your working folder yet.git fetch origin - Rebase your local branch: This tells Git: "Take my local commit, temporarily hide
it, update my folder to match GitHub's newest version, and then apply my local commit exactly on
top."
git rebase origin/main - Push the perfectly merged timeline: Because you rebased, your history is a clean
straight line. You can now safely push your local work to GitHub.
git push origin main📸 Click here to what it should look like
Experiment 6. Collaboration and Remote Repositories
Task: Set up a new workspace for Lab 6, initialize a Git repository, create a feature branch, and write the command to merge "feature-branch" into "main" while providing a custom commit message for the merge.
Solution Steps:
Understanding the
process: When you merge a branch, Git often performs a "fast-forward" merge if no other
changes have been made to the main branch. A fast-forward merge does not create a new merge commit. To
attach a custom commit message to a merge, you must force Git to create a merge commit
using the --no-ff (no fast-forward) flag.
--no-ff flag guarantees that a specific merge commit object is
created, preserving the historical existence of the feature branch and allowing you to leave a detailed
custom message explaining the merge.
Git Bash, and
press Enter.
- Create a new folder for Lab 6:
mkdir lab6 - Navigate into the new folder:
cd lab6 - Initialize the repository:
git init - Make an initial commit on main: You need a base commit before creating new
branches.
Create a starting file:echo "Starting point for lab 6" > main_file.txt
Stage the file:git add .
Commit the file:git commit -m "Initial commit on main branch" - Create and switch to the feature branch:
git checkout -b feature-branch - Make changes on the feature branch: Create a file, stage it, and commit.
echo "Adding remote collaboration features." > collab.txtgit add .git commit -m "Added collab features" - Switch back to the main branch: Return to the main timeline to prepare for the
merge.
git checkout main - Merge with a custom commit message: Use the --no-ff flag combined with the -m
flag to force a merge commit and attach your custom explanation.
- --no-ff Creates a merge commit, preserving a clear record of when the feature branch was integrated.
- -m Adds your custom merge commit message.
git merge feature-branch --no-ff -m "Merge feature-branch into master" - (Optional) Connect and Push to Remote:
git remote add origin https://github.com/yourusername/your-repo-name.git
git push -u origin main
git merge feature-branch -m "message" Allows a fast-forward merge if possible.
git merge feature-branch --no-ff -m "message" Forces a merge commit, even if fast-forward is possible.
--no-ff and
attached a custom message, ensuring your project history explicitly documents when and why the feature
branch was integrated.
Experiment 7. Git Tags and Releases
Task: Set up a new workspace for Lab 7, initialize a Git repository, make an initial commit, and write the command to create a lightweight Git tag named "v1.0" for a commit in your local repository.
Solution Steps:
Understanding the process: In Git, a tag acts like a permanent bookmark for a specific point in your repository’s history. It is generally used to capture a release point (like a software version). A lightweight tag is the simplest form of a tag—it is just a pointer to a specific commit, without saving extra metadata like the tagger's name, email, or a message.
Git Bash, and
press Enter.
- Create a new folder for Lab 7:
mkdir lab7 - Navigate into the new folder:
cd lab7 - Initialize the repository:
git init - Make an initial commit: You must have at least one commit in your history before
you can create a tag.
Create a starting file:echo "Version 1.0 ready for release" > release_notes.txt
Stage the file:git add .
Commit the file:git commit -m "Prepare initial release" - Create the lightweight tag: Run this command to attach the tag "v1.0" to the commit
you just made.
git tag v1.0 - Verify the tag was created: List all tags in your repository to confirm it worked.
git tag - (Optional) Connect and Push everything to Remote: Remember to push your tags
explicitly!
git remote add origin https://github.com/yourusername/your-repo-name.git
Push the main branch:git push -u origin main
Push the newly created tag:git push origin v1.0
git tag v1.0
Creates a lightweight tag. It is essentially just a pointer to a commit. Best for private
or temporary object labels.
git tag -a v1.0 -m "Release version 1.0"
Creates an annotated tag. This creates a full object in the Git database containing the
tagger's name, email, date, and a tagging message. Recommended for public releases.
Experiment 8. Advanced Git Operations
Task: Set up a new workspace for Lab 8, initialize a Git repository, create a series of commits on a separate branch, and write the command to cherry-pick a range of commits from "source-branch" to your current branch.
Solution Steps:
Understanding the
process: Cherry-picking allows you to pick specific commits from one
branch and apply them to another without merging the entire branch. When you want to pick a
range of commits (from commit A to commit B), you can use the syntax A..B.
However, because standard Git range syntax excludes the starting commit, we often use A^..B
to include commit A in the cherry-pick.
git log.
Git Bash, and
press Enter.
- Create a new folder for Lab 8:
mkdir lab8 - Navigate into the new folder:
cd lab8 - Initialize the repository:
git init - Make a base commit on main:
echo "Base project files" > base.txtgit add .git commit -m "Initial commit on main" - Create and switch to the source-branch: This is where we will simulate our work.
git checkout -b source-branch - Create a series of commits: We will make three separate commits to cherry-pick
later.
Creating first file, adding it and commiting at Aecho "Feature part 1" > feat1.txtgit add .git commit -m "Commit A"
Creating second file, adding it and commiting at Becho "Feature part 2" > feat2.txtgit add .git commit -m "Commit B"
Creating third file, adding it and commiting at Cecho "Feature part 3" > feat3.txtgit add .git commit -m "Commit C" - View your commit hashes: Run git log to see the history. Note down the hash for
Commit A and Commit C.
git log --oneline - Switch back to the branch you want to copy the commits into (main):
git checkout main - Cherry-pick the range of commits: Replace
<hash-A>and<hash-C>with the actual hashes from yourgit log. The^symbol ensures Commit A is included in the range.git cherry-pick <hash-A>^..<hash-C> - (Optional) Connect and Push to Remote: If you want to push this to GitHub, add your
own
remote origin
git remote add origin https://github.com/yourusername/your-repo-name.git
thne push the codegit push -u origin main
git cherry-pick <hash>
Copies a single specific commit to your current branch.
git cherry-pick <hash-A>..<hash-B>
Copies everything after Commit A up to Commit B (Excludes A).
git cherry-pick <hash-A>^..<hash-B>
Copies the entire range from Commit A through Commit B (Includes A).
Experiment 9. Analysing and Changing Git History
Task: Set up a new workspace for Lab 9, initialize a Git repository, create a commit, and use Git commands to view the details of that specific commit, including the author, date, and commit message.
Solution Steps:
Understanding the
process: To inspect a specific moment in your project's history, Git provides tools to view
a commit's metadata (who, when, why) and its exact code changes. The primary command for this is
git show, which requires the unique commit ID (SHA-1 hash) to identify
which commit to display.
Git Bash, and
press Enter.
- Create a new folder for Lab 9:
mkdir lab9 - Navigate into the new folder:
cd lab9 - Initialize the repository:
git init - Make a base commit: We need at least one commit in our history to analyze.
Creating a file, adding it, and committing:echo "Content to analyze" > history_file.txtgit add .git commit -m "Added history_file.txt for analysis" - Find the Commit ID: Run
git logto see your repository's history and locate the hash of the commit you just made.(Copy the 7-character string that appears at the start of the line).git log --oneline - View the specific commit details: Replace
<commit-id>with the actual hash you found in the previous step. This command will output the author, date, message, and the specific file changes (diff).git show <commit-id> - (Optional) View ONLY the metadata (No file diffs): If you want to see the author,
date, and message without seeing the lines of code that changed, use the log command limited to 1
commit.
git log -1 <commit-id>
git show <commit-id>
Shows everything: The author, date, full commit message, AND the exact lines of code that were added
or removed (the diff).
git log -1 <commit-id>
Shows only the metadata: The author, date, and full commit message. The -1 flag tells
Git to limit the output to just one commit.
git log --stat <commit-id>
Shows the metadata plus a summary of which files were changed and how many lines were
inserted/deleted (without showing the actual code).
Experiment 10. Analysing and Changing Git History
Task: Set up a new workspace for Lab 10, initialize a Git repository, create some commits, and write the command to list all commits made by the author "Pruthviraj" between "2025-01-01" and "2026-12-31".
Solution Steps:
Understanding the
process: As a project grows, finding specific changes becomes difficult. Git's
log command is highly filterable. You can combine flags like --author to
search by name and --since / --until (or --after /
--before) to filter commits by specific dates.
Git Bash, and
press Enter.
- Create a new folder for Lab 10:
mkdir lab10 - Navigate into the new folder:
cd lab10 - Initialize the repository:
git init - Create sample commits to filter: Let's make a few commits so we have data to search
through.
echo "First log entry" > log.txtgit add .commit 1 is done, same way wll do the commit 2git commit -m "Commit 1"echo "Second log entry" >> log.txtgit add .git commit -m "Commit 2" -
Check your user name first.
git config --global user.name
Filter commits by Author and Date Range: Use the combination of author, since, and until flags to precisely filter your history.
replace your name here in the quotesgit log --author="Pruthviraj" --since="2025-01-01" --until="2026-12-31" - (Optional) Make the output easier to read: When filtering large repositories,
adding --oneline makes the output much cleaner.
replace your name here in the quotesgit log --author="Pruthviraj" --since="2025-01-01" --until="2026-12-31" --oneline
--author="Name"
Filters the commits to only show those where the author matches the specified string.
--since="YYYY-MM-DD"
(or --after)
Shows commits made after the specified date.
--until="YYYY-MM-DD"
(or --before)
Shows commits made before the specified date.
Experiment 11. Analysing and Changing Git History
Task: Set up a new workspace for Lab 11, initialize a Git repository, create a series of commits, and write the command to display exactly the last five commits in the repository's history.
Solution Steps:
Understanding the
process: When working on a project with a long history, typing just git log
will display every single commit, which can overwhelm your terminal. Git allows you to limit the output
by simply appending a hyphen and a number (e.g., -5) to the log command, instructing it to
only retrieve the most recent commits.
-3 for
the last three commits, or -10 for the last ten).
Git Bash, and
press Enter.
- Create a new folder for Lab 11:
mkdir lab11 - Navigate into the new folder:
cd lab11 - Initialize the repository:
git init - Create multiple sample commits: To prove the command works, let's quickly generate
6 distinct commits using a chained command.
echo "1" > data.txt && git add . && git commit -m "Commit 1"echo "2" >> data.txt && git add . && git commit -m "Commit 2"echo "3" >> data.txt && git add . && git commit -m "Commit 3"echo "4" >> data.txt && git add . && git commit -m "Commit 4"echo "5" >> data.txt && git add . && git commit -m "Commit 5"echo "6" >> data.txt && git add . && git commit -m "Commit 6" - Display the last five commits: Use the numerical limit flag. You should see Commits
2 through 6, but Commit 1 will be hidden.
git log -5 - (Optional) Display the last five commits in a cleaner format: Combine the limit
flag with the oneline flag for a highly readable summary.
git log -5 --oneline
git log -5
The standard shorthand to show exactly the 5 most recent commits in detailed format.
git log -n 5
The explicit syntax for limiting output. It does exactly the same thing as -5, but some
users find it easier to remember that "n" stands for "number".
Experiment 12. Analysing and Changing Git History
Task: Set up a new workspace for Lab 12, initialize a Git repository, create some commits, find a specific commit ID, and write the command to safely undo the changes introduced by that commit.
Solution Steps:
Understanding the
process: When you realize a previous commit broke your code, you need a way to undo it.
While you could use git reset to completely erase history, this is dangerous if you have
already shared your code with others. The safer, preferred method is
git revert. Instead of deleting the bad commit, it creates a brand new
commit that does the exact opposite of the bad one—safely rolling back the changes while
preserving the project's timeline.
<commit-id> or
abc123. In a real scenario, you must replace this with the actual SHA-1 hash of the commit
you wish to undo, which you can find using git log.
Git Bash, and
press Enter.
- Create a new folder for Lab 12:
mkdir lab12 - Navigate into the new folder:
cd lab12 - Initialize the repository:
git init - Create a base commit:
echo "Good code" > project.txtgit add .git commit -m "Initial good commit" - Create a "bad" commit that we want to undo:
echo "This line breaks everything!" >> project.txtgit add .git commit -m "Added a bug" - Find the ID of the bad commit: Run the log to see the history. Note down the
7-character hash for the "Added a bug" commit.
git log --oneline - Revert the specific commit: Replace
abc123with the actual hash you found in step 6. Git will automatically open your default text editor asking you to confirm or edit the revert message. Save and close the file to complete the revert.git revert abc123This opens your default editor for commit name if your editor is buit in git editorpress :wq to exit the code editor
if your code editor is visual-studio-code then just close editor to give the commit message
- (Optional) Skip the editor: If you don't want Git to open a text editor and are
happy with the default system-generated revert message, add the
--no-editflag.git revert abc123 --no-edit - Verify the fix: Check the contents of your file and view the log. You will see a
new commit added to the top of your history named "Revert 'Added a bug'", and your file will be back
to normal.
cat project.txtgit log --oneline
git revert <commit-id>
(Safe for collaboration) Creates a new commit that nullifies the changes of the
specified commit. The original bad commit stays in the history for transparency.
git reset --hard <commit-id>
(Dangerous) Permanently deletes the history back to the specified commit. If you
use this on commits you have already pushed to GitHub, it will cause major conflicts for anyone else
working on the project.
git revert to generate an inverse
commit, cleanly rolling back an unwanted change while preserving an accurate, non-destructive timeline
of the project's history.