How to add and commit files in Git?

In this example, we will add a few files and commit them one by one and complete all of them, and check logs

Commands we use here are:

  • touch <file>Create a file in bash terminal
  • git add .Stage the file to the git
  • git commit -m”<Commit message>”Commit the changes with a message

Let’s get started

Step #1. Create the first file, stage the file and commit it.

Here we will use an Ubuntu system with git installed. Also, have a git repo created. COmmands such as git add and git commit will be used. Let us dive in.

[email protected]:~/codetryout-code$ touch file1
[email protected]:~/codetryout-code$ 
[email protected]:~/codetryout-code$ git add .
[email protected]:~/codetryout-code$ git commit -m"commit 1"
[master (root-commit) b36945a] commit 1
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 file1
[email protected]:~/codetryout-code$ 

We have just created one file, named: file1, added(staged) that new file to git, and committed that file with a comment: commit 1.

Step #2. Create the second file, stage the file and commit it.

Similar to step 1, we are going to add another file, stage, and commit it now.

[email protected]:~/codetryout-code$ touch file2
[email protected]:~/codetryout-code$
[email protected]:~/codetryout-code$ git add .
[email protected]:~/codetryout-code$ git commit -m"commit 2"
[master efc1357] commit 2
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 file2
[email protected]:~/codetryout-code$

Step #3. Create the third file, stage the file and commit it.

Repeating the steps similar to step one and two. Adding a new file, staging, and committing.

[email protected]:~/codetryout-code$ touch file3
[email protected]:~/codetryout-code$ 
[email protected]:~/codetryout-code$ git add .
[email protected]:~/codetryout-code$ git commit -m"commit 3"
[master 6815e84] commit 3
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 file3
[email protected]:~/codetryout-code$ 

Step #4, View your commit logs

To review your commit history, use git log command. Here is an example:

[email protected]:~/codetryout-code$ git log
commit 6815e845f13046570aaccdb66aee38caa68a6a60 (HEAD -> master)
Author: Ubuntu <[email protected]>
Date:   Tue Jan 5 22:03:36 2021 +0530

    commit 3

commit efc13573a8b93ce10d74980b0ad4ac510e63734b
Author: Ubuntu <[email protected]>
Date:   Tue Jan 5 22:03:20 2021 +0530

    commit 2

commit b36945a7bc5df78259a97a6bc6c90224e56c1434
Author: Ubuntu <[email protected]>
Date:   Tue Jan 5 22:02:54 2021 +0530

    commit 1
[email protected]:~/codetryout-code$

Please do let us know if you have questions. This test case is done in an Ubuntu terminal, however the same will work in any Git command line, such as Git Bash, Linux/CentOS and Docker containers with git client.