Git is an essential version control system used by DevOps Training worldwide to track changes, collaborate on projects, and maintain code integrity. Whether you’re working solo or as part of a team, understanding key Git commands can streamline your workflow and prevent common pitfalls.
In this guide, we’ll explore the essential Git commands every developer should know.
Before using Git, configure it with your user information:
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
This ensures that all your commits are associated with your identity.
To start tracking a new project, initialize a Git repository:
git init
This creates a .git directory, where Git stores all version control data.
To work on an existing project, clone a repository:
git clone <repository-url>
This downloads the project and its entire history onto your local machine.
To check which files have been modified, added, or deleted, use:
git status
This command helps track your progress before committing changes.
To stage specific files for commit:
git add <file-name>
To stage all changes:
git add .
This prepares files for the next commit.
Once files are staged, commit them with a descriptive message:
git commit -m "Your commit message"
This saves changes locally in the Git history.
To see a list of previous commits:
git log
For a concise view:
git log --oneline
To create a new branch:
git branch <branch-name>
To switch to another branch:
git checkout <branch-name>
Alternatively, create and switch to a new branch in one command:
git checkout -b <branch-name>
To merge changes from another branch into the current one:
git merge <branch-name>
Resolve conflicts if necessary and commit the merge.
To upload commits to a remote repository:
git push origin <branch-name>
To fetch and integrate updates from a remote repository:
git pull origin <branch-name>
To discard unstaged changes in a file:
git checkout -- <file-name>
To reset the staging area:
git reset HEAD <file-name>
To undo the last commit while keeping changes:
git reset --soft HEAD~1
To permanently remove the last commit:
git reset --hard HEAD~1
If you need to save changes without committing:
git stash
To apply stashed changes:
git stash apply
To remove the stash after applying:
git stash drop
To create a new tag:
git tag -a v1.0 -m "Version 1.0"
To push tags to the remote repository:
git push origin --tags
Mastering these Git commands will help you efficiently manage your code, collaborate with teammates, and avoid common pitfalls in version control. Whether you’re a beginner or an experienced developer, understanding Git is an essential skill in modern software development. Keep practicing and experimenting with Git to unlock its full potential!