Git is a powerful version tracker that allows developers to keep track of changes in their source code. It is a widely used tool by open source developers. Although it was designed to coordinate programming tasks, Git can track any set of files effectively. Moreover, it was developed by Linus Torvalds, the man behind the Linux kernel.
So, if you are an open-source developer adding features to your software over time or are working with multiple peers to develop cutting-edge enterprise products, Git can be the ideal tracking system for your job. Stay with us to learn some of the fundamental git commands that will greatly simplify your development cycles.
Practical Git Commands for Open-source Developers
The git CLI offers a considerable number of git commands to make the software development process easier for developers. Our editors have outlined some of the most useful such commands for the convenience of our readers. So, continue reading and discover them at your own pace.
1. Configure User Profile
You can configure your git profile using the git config command. The least you can set up is the username and the email address. Git allows users to configure these policies either globally or on a project basis. Use the below command to set each repository’s user and email address.
$ git config user.name "USERNAME" $ git config user.email "[email protected]"
Add the --global
option to set these policies globally.
$ git config --global user.name "USERNAME" $ git config --global user.email "[email protected]"
2. Initialize Git Repositories
A git repository or simply repo is the root directory for your open source projects. It contains the source files, sub-directories for objects, heads, and tags. You can easily initialize a git repo using the following command.
$ git init
It is one of the most common git commands you will use. You can now start adding your source files and tinker with them as you want.
3. Add Project Files
Adding files to existing projects is very easy using git. You can easily add all modified files/directories to the tracking system using the git add command. Take a quick look at the below example to see how this works.
$ git add file $ git add *.php
When you issue the git add command, it will add all files to the project index from the current working directory. You can specify particular files as done in the first example. The second example will add all PHP files to the index. Git will mark them for staging.
4. Verify Added Files
You can verify the files staged during the next commit using the git status command. It will show all the new files or files that have been changed.
$ git status
Run the above command whenever you want to see the details. It will display a summarized list of all files staged in the upcoming commit.
5. Commit Changes to the Repository
When you commit your changes, git takes a snapshot of your codebase. It is how git keeps track of your changes and provides version control. You will need to use the git commit command for this.
$ git commit
When you run the above command, git will ask you to enter some information, such as adding a description. It will invoke the default Linux editor you set up during your git installation. Use the below command to avoid this indiscretion.
$ git commit -m "First Commit"
So, you can add the description directly if you use the -m option.
6. Display the Logs
You can check the logs whenever you want to see the changes you’ve made to your repository. Use the git log command from the Linux terminal to do this.
$ git log $ git log --file
The first example will show generalized information on your git commits. Use the second command to view changes in a specific file only. You can add more options like the --log-size
option or even search commits using regular expressions.
7. Verify Project Branches
A git branch represents an independent line of development in your project. You can easily check your current branch using the git branch command. It will display the active branch where you develop new features or modify older ones.
$ git branch
The output will mark the current branch using an asterisk (*) sign.
8. Reset Project Branches
You can easily reset the current repository and working directory to a known state. The git reset command will adjust the HEAD reference to a specific commit and will update the index to match this particular commit accordingly.
$ git reset
Use the following command to perform a soft reset of your current branch.
$ git reset --soft
You can also perform a hard reset in a similar way. Simply replace --soft
with the --hard
option, as demonstrated in the below example.
$ git reset --hard
9. Add a New Branch
Adding a new branch allows you to work on newer features independently. You can easily add a branch using the git branch command. Add the branch name, as shown below.
$ git branch new-feature
Verify whether the addition was successful or not by issuing the git branch command. It should display the newly created branch called new-feature. However, you can not add more than one branch using the same branch name. It will cause a fatal error.
10. Switch between Branches
You can easily switch between various branches of your project using the checkout command. It is one of the most used git commands during software development. Take a quick look at the next example to see how this works.
$ git checkout new-feature
This command will notify you that the branch has been switched successfully. You can also verify this using the git branch command shown earlier.
11. Delete a Project Branch
When you successfully develop new features, you want them to be added to the git master branch. Once this is done, you can go and remove that branch completely. The -D
option of the git command allows us to do this very easily.
$ git checkout master $ git branch -D new-feature
You need to get out of the branch first to delete it successfully. Otherwise, git will throw an error.
12. Check Differences among Commits, Trees, and Files
The git diff command allows us to view the changes in two multiple files, the working tree and the index tree, between commits and between blob objects. It is one of the most fundamental git commands used to track code base changes.
$ git diff $ git diff new-feature master
The first example will display the changes between the working tree and the index tree. The second example will display changes between the master branch and the new-feature branch.
13. Merge Two Branches
You can easily merge two different development branches using the git merge command. It will combine two branches into one unified branch. You can use the git merge command for several purposes. Look at the example below to see how we can use them.
$ git merge fixes new-feature $ git merge -s ours obsolete $ git merge --no-commit main
The first example merges two branch new-feature and fixes to create a single branch. The second example merges the obsol] branch to the current development branch using the ours
strategy. The final example merges the branch main to the current branch but disables automatic commit.
14. Revert Existing Commits
Sometimes, you may decide that some of your commits are no longer required. In such cases, it is better to revert these commits than to modify the branch altogether. The git revert command lets us do exactly this.
$ git revert ad9ef37d88ad4gfyg90aa6a23f71e775982f4b $ git revert HEAD~3
The first example will revert the changes introduced by the commit id f5ad9ef37d88ad4gfyg90aa6a23f71e775982f4b
. The second example relapses the fourth last commit in HEAD and performs a new commit.
15. Stash Working Directory
You can temporarily save the current state of your working directory someplace and come back to it later when you want. This is called stashing in git terminology. It simply stores the state of your working directory and the index so that you can work on something new.
$ git stash
Developers usually use this command when caught in a messy situation. It allows them to store the untidy workflow and come back to solve it later. Use the stash list command to view your stash list.
$ git stash list
16. Clone a Repository
One of the best things about open source is that you work on other people’s code as if it were your own. Git makes it easy to download an existing project using the git clone command. Look at the illustration below to see how this works in real life.
$ git clone <GIT:URL> $ git clone git://example.com/git.git/ test-dir
This will download the said project into the test-dir
directory of your system.
17. Pull New Updates
Real-life projects are evolving all the time. Suppose you cloned a repo earlier from a remote repository. What will you do when the developers update new features for that repository? It is inconvenient to clone the same repo over and over into your local machine. The git pull command saves you from this.
$ git pull
This command will update the local version of your project with any new changes made by the collaborators. Remember to change your working directory to the project directory before pulling the latest updates.
18. Push Your Updates
Once you are done working with your updates, you can add them to the remote repository by pushing the. The difference between git push and git commit is that when you commit some changes, they’re added to your local repo rather than the remote repo.
$ git push
This command will add your updates to the project’s remote repository. You will usually use pull and push to collaborate with remote developers. So, it’s important you master them perfectly.
19. Display Remote Repositories
The git remote command allows us to manage a set of tracked repositories conveniently from the Linux terminal. You can use it to clone only some selected branches.
$ git remote $ git remote --verbose
The first example will display all remote repositories that are currently configured. Adding the –verbose flag shows us detailed information about this.
20. Connect to Remote Repositories
You can set up remote repositories so that your local repo is connected to a remote server. By doing this, you will be able to push your local changes to the remote server directly. Take a quick look at the following illustration to see how this works in practice.
$ git remote add origin <server>
The above command will add ‘origin’ as the remote name to the server. You can discover the server URL by exploring the Source sub-tab of your GitHub repo.
21. Add Tags to Your Project
Tags allow you to mark significant events in your open source projects. Developers often use them to mark new relapses or bug fixes. Take a close look at the below git commands to learn how to add tags to your projects using git.
$ git tag 1.0.0 <commit-id>
This command adds the tag 1.0.0 to the specific commit. You can grab the commit-id
using the command below.
$ git log
Push the tag to your remote repo by using the following command.
$ git push origin --tags
You need to specify the –tags option explicitly. Otherwise, the tag will only be added to your local repo, not to the remote repo.
22. Fetch Remote Data
Another common git command you will often use is fetch. It is very useful for a number of reasons. Firstly, fetch only retrieves new data/references but not merges them to your local branch. So, you can be assured that the working copy of your local repo will remain safe and sound.
$ git fetch origin
It is an excellent way of checking the recent progress of a remote codebase without breaking your own version of the project. Once you’re certain that all new data are good to go, simply merge them to your local branches.
23. Restore Non-Committed Changes
The git restore command allows developers to restore any non-committed changes in their projects. These are changes that you’ve made to your working version of the project or contents in your local index. You can use this command to either revert changes in your working copy, make changes in the index, or do both.
$ git restore --staged test.php $ git restore --source=HEAD --staged --worktree test.php
The first command will restore the file test.php in the index, and the second command will restore both the index and the current working directory of your project.
24. Remove Files
Sometimes, you may want to remove some files from your working tree or the project index altogether. You can use the git rm command to do this. However, this command will not remove the specified files from your working directory. Use the Linux rm command to do that.
$ git rm *.php $ git rm -r dir/ $ git rm --cached *.php
The first command deletes all PHP files from the working tree and index. The second command deletes everything from the dir/ directory. The last command will delete all PHP files only from the index, not the working tree.
25. Move or Rename Files
You can move or rename files using git, just like you’d do using the Linux mv command. It is actually a shorthand for busy developers built right into Git.
$ git mv test.py new-test.py
The above command simply does the following Linux operations.
$ mv test.py new-test.py $ git add new-test.py $ rm test.py
So, you can use the git mv command to save yourself from typing a bunch of extra Linux terminal commands.
26. Clean Untracked Files
Untracked files are files that are not under the git version control system. You will stumble across such files quite often when working on large-scale projects. You can remove them using several methods, including git reset and checkout. However, using the git clean command is the most suitable way.
$ git clean fatal: clean.requireForce defaults to true and neither -i, -n, nor -f given; refusing to clean
The above command failed because this is how git is configured in my system. You can get around this issue by adding the -n, -i, or -f option.
$ git clean -n
27. Optimize Local Repositories
One of my favorite git commands is gc. It is used for garbage collection and will help you reduce the size of your local repos. You should use this command frequently if you’re working on extensive projects.
$ git gc
The git gc command runs extremely fast and cleans up unnecessary files around your local repository. It is one of the best optimization methods due to its speed and efficiency. You can also use the --aggressive
option to increase the optimization. However, it will require more time to complete.
28. Archive Local Repositories
You can easily archive your local repos by using the git archive command. It allows developers to store their projects someplace safe. You can transfer this archive over the network or store it on the Linux file system.
$ git archive --output=test --format=tar master
The above command stores the repo in a tar file named test. You can omit the --format
option if you want. In this case, git will try to infer the archive format from its name. There are many more options available for this command.
29. Search for Patterns
When working on large projects, you’ll often need to search for different things. Thankfully, the git grep command allows us to search for specific patterns in our repos and makes development much easier. It works similarly to standard Linux grep commands, with a few git-specific features.
$ git grep -iw 'import' master
This command displays all lines containing ‘import’ in our master branch. It searches in a case-insensitive way. The following command will search for the given pattern in all the commits and branches.
$ git grep 'import' $(git rev-list --all)
This is one of the best git commands to master if you’re collaborating on large-scale projects.
30. Manage Working Trees
Developers can work with multiple working trees in Git. This is useful when checking out more than a single branch of your project. Check out the following git commands to see how to manage working trees in git.
$ git worktree list $ git worktree add new-branch $ git worktree remove new-branch $ git worktree prune
You can display the current working trees using the first command. Use the second command to add a new “linked working tree” and the third command to remove that tree. The final command allows you to prune the working tree information.
31. Prune Untracked Objects
Sometimes you may want to delete objects that are no longer being tracked by git. Git provides a simple command to do this. The git prune command will only delete untracked objects from your object database, not the references themselves.
$ git prune --dry-run $ git prune --verbose --progress
The first command does not delete anything and will only show objects that prune would remove. The second command provides verbose output as well as a progress report during the deletion period. You may use prune commands to optimize your repos alongside the git gc command.
32. Pack Unpacked Objects
In git, packs are a collection of individually compressed objects. Git applies delta compression on these objects and stores them in a single file. They are used to reduce the load on your Linux filesystem or mirror systems. The git repack command allows users to create new packs consisting of objects that do not sit inside existing packs.
$ git repack
You can use this command alongside git gc and git prune to optimize your git repos.
33. List Unpacked Objects
You should not repack your objects frequently unless there are too many unpacked objects. The git count-objects command is a simple but useful method of viewing the number of unpacked objects and how much disk space they consume.
$ git count-objects
Use the above command to determine whether it’s time for a git repack or not. You may add the --verbose
flag for getting detailed information and the --human-readable
flag to display the size in a conventional manner.
34. Validate the Object Database
Git was developed as a filesystem in its early days. It has a useful command called fsck, which acts very similar to the Unix fsck. You can use this command to verify connectivity and perform integrity checks for your objects.
$ git fsck
Running the above command will display any corrupted objects found in your object database. It is one of the most useful git commands for finding missing or bad objects.
35. Display Changes for Each Commit
The git whatchanged
command is another of our favorite git sub-commands. It is a simple but effective way of viewing what changes each individual git commit introduces to our project.
$ git whatchanged
This git command will display information using commit logs and diff output. Overall, it is quite similar in operation to the git log command.
36. Summarize Log Information
You can also use the git shortlog
command for viewing histories. The main idea behind this command is to include the output in release announcements. Take a quick look at the following command to see how this works.
$ git shortlog $ git shortlog --email --summary
Adding the --email
option will display the emails of each author. The --summary
option will suppress the usual output and will only show the number of commits.
37. Manage Configuration Options
There are a huge number of configuration options available to git. You can use the git config command to query, set, or replace various options. Changes can be made to both specific repos and the global configuration.
$ git config --list
The above command will list all currently set configuration options in git. You can easily add or remove new options. Follow the help page of the config sub-command to learn how to do these tasks.
$ git config --help
38. Consult Git Help
The help page of git or any other Linux terminal commands provides summarized information on all available options. It should be the first place to visit when you face trouble with git. Take a quick look at the following commands to learn how to invoke the git help page.
$ git help $ git --help
So, you can consult the git help page by utilizing either the Unix-style --help
option or the help sub-command built into git. Additionally, git also provides help pages for sub-commands.
$ git <command> --help $ git commit --help
39. Consult Manual Page
The man page contains in-depth information about the git version control system and all of its sub-commands. You can view it by following the syntax below.
$ man git $ man git commit
So, you can also view manuals for individual sub-commands like you can with the help page.
40. Display Version Information
You can use the following simple command to view which version of git is installed on your system. Since git has evolved largely over time, there are significant differences among various git versions.
$ git --version
Simply use the above command to get the specific version of git available on your machine.
Ending Thoughts
Git has cemented its position as the de-facto version control system thanks to its practical design and diverse feature set. Although there are some great alternatives, such as Mercurial and CVS, a large number of practical git commands make it more versatile than its competitors.
Our editors have gone to extreme lengths to outline the most practical commands for you. Hopefully, you’ve obtained the essential insights you were looking for from this guide. Feel free to ask us questions if you’ve doubts regarding a particular command. Thanks for staying with us throughout this long guide.
Nice guide. Bookmarked!