What is Git
We’ve all been there: you update a perfectly working codebase to add features or optimize it, and suddenly, things start breaking. You try to fix it, but eventually, you just want to go back to that stage when everything was working perfectly.
But HOW?
Hello, I’m Git—I’ve got you covered!
Git
A command-line tool, that acts as a version control software.
It tracks the versions and changes made to a repository, allowing you to easily revert to previous states when things go wrong.
Let's explore some basic Git commands:
Scenario:
You create a folder named "robo".
git init
- Initializes Git in your folder.Navigate to the robo folder and run this command to set it up for Git version control.
Now, create a file body.txt in this folder with the text "abc" in it.
git status
- shows the status of the folderAfter adding a new file, running git status will show you something like this:
-
This output means that the new file is untracked and needs to be added to the staging area.
git add
- Track the FileTo start tracking a new file body.txt, use the
git add body.txt
command:-
Now, try running the
git status
command -
You’ll see body.txt listed under "Changes to be committed," indicating that Git is now tracking the file.
git commit -m message
- Commit the changesTo commit the changes, use the git commit command. Include a descriptive message in quotes to explain what changes were made:
-
This command will commit the body.txt file with the provided commit message.
Now let's goto the body.txt and add some more text to abc, like abcfgh.
Add and commit the body.txt.
Now say we figured out that we made a mistake in this file like instead of "abcdef" we written "abcfgh", so we want to go back to the previous correct stage. (This change is very small but think of it like when we have many of such changes in many files).
git log
- Show the history of the commitsThis will display all the commits made for this folder or repository with some details like who commited, when and commit-code.
-
So we want to go to the previous commit
git checkout -- body.txt
-Identify the Commit Hash: Use git log to find the hash of the commit you want to revert to. From above it is "1234567890abcdef1234567890abcdef12345678"
So,
git checkout 1234567890abcdef1234567890abcdef12345678 -- body.txt
The body.txt file should now have the text abc as it was in the previous commit.
Hope this helps you understand the basic flow of using Git for version control!
Subscribe to my newsletter
Read articles from Rohith Kola directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by