Skip to content

Git - Perform Changes

Jerry clones the repository and decides to implement basic string operations. So he creates a string_utils.c file. After adding the contents, string_utils.c will look like as follows:

#include <stdio.h>
#include <string.h> // For strcmp, strcpy if used later
// A custom function to calculate string length
size_t my_strlen(const char *s)
{
const char *p = s;
while (*p) {
++p;
}
return (p - s);
}
int main(void)
{
int i;
char *s[] =
{
"Git tutorials",
"Tutorials Point"
};
printf("Demonstrating my_strlen:\n");
for (i = 0; i < 2; ++i) {
printf("Length of \"%s\" = %zu\n", s[i], my_strlen(s[i]));
}
return 0;
}

He compiled and tested his code (e.g., gcc string_utils.c -o string_app) and everything is working as expected. The compiled output string_app is typically not version-controlled and would be added to a .gitignore file in a real project. Now, he can safely add the source code changes to the repository.

The git add command adds file contents to the staging area (also known as the index).

[jerry@devbox project]$ git status -s
?? string_utils.c
[jerry@devbox project]$ git add string_utils.c

Initially, git status -s shows ?? before string_utils.c, indicating it’s an untracked file. After git add string_utils.c, Git starts tracking this file and its current contents are staged for the next commit.

Jerry has added the file to the staging area. The git status command will now show the file as staged.

[jerry@devbox project]$ git status -s
A string_utils.c

To commit the staged changes, he uses the git commit command with the -m option for a commit message. If the -m option is omitted, Git will open a text editor to write a more detailed commit message. It’s a best practice to write clear and concise commit messages that explain the why behind the changes.

[jerry@devbox project]$ git commit -m "Implement my_strlen function and main demo"

The above command will produce output similar to the following:

[main abc1234] Implement my_strlen function and main demo
1 file changed, 25 insertions(+)
create mode 100644 string_utils.c

After committing, he runs the git log command to view the commit history. It displays information for all commits, including their commit ID (SHA-1 hash), author, date, and commit message.

[jerry@devbox project]$ git log

The above command will produce output similar to the following (newest commit first):

commit abc1234b140dad24b2c35b15cc7e26a6f02d2277 (HEAD -> main)
Author: Jerry Mouse <jerry@example.com>
Date: Mon Jan 15 10:00:00 2024 +0000
Implement my_strlen function and main demo
commit 19ae20683fc460db7d127cf201a1429523b0e319
Author: Tom Cat <tom@example.com>
Date: Sun Jan 14 09:30:00 2024 +0000
Initial commit