Stage changes and commit them in Git

We saw earlier how to initialize an empty Git repository and configure it. Now it is time to start our project by adding new source code files and editing them. By definition, Git will follow the changes we make to every file. Git gives the possibility to assemble a list of changes and then mark them as a point in the history of the repository. This is called a commit

So, a commit is basically a coherent list of changes, that marks a feature we've added, a bug we've fixed, or just some refactoring we have done.

We stage changes by executing the command : git add list_of_files_here

We then commit the list of changes we have staged with : git commit -m "commit message here" list_of_files_here

Before showcasing these commands, a very important command in Git is git status. Git status will show us a list of all the files that have changed or have been created (in red color on the command line), along with the staged files for commit (in green)

Let's now change a file, and add other two files file3.txt and file4.txt but let's assume file4.txt is not related to the current feature we are working on.

So what we want to do is add both file1.txt and file3.txt but not file4.txt : git add file1.txt file3.txt

We then commit using the command : git commit -am "changed file1.txt and added file3.txt"

The a option is for all, it means we want to commit all the files that are in the index, rather than specifying them one by on in the commit command

We then check file4.txt is still in the staging area by using git status

It is important to gather only the changes necessary to the current feature we are working on, and commit them once. It keeps our commit coherent and hence does not overwhelm your colleague developer who is going to review your commit

you can check the list of your commits using the command git log --oneline :

We can see the two commits in the output of this command, along with a hash that represents uniquely each commit in the history of the repository.

I hope you learned something in this tutorial. In subsequent tutorials, we will delve deeper with more tips about add and commit commands.

Happy learning !