Add Specific file using Git add

When we set up a project, we often use the git add . command to add all files in the project folder to our first git commit. This is a quick and easy way to commit everything. But many beginners end up using git add . every time, without realising that it adds everything even the files that you might not want to commit. It’s important to use the command carefully.

 

Why Overusing git add . Can Be a Problem

If we keep adding everything with git add . without checking, we might end up committing code that’s unrelated to the task. This can make it difficult to track changes in the future and wont be able to review the history eaily. So If we need to go back to an previous version, it might be difficult if commits aren’t well-organized.

 

How to Add Files Selectively

Sometimes, we’re working on multiple things at time like developing a new feature and also fixing a typo or adjusting some CSS. In such cases, these changes have different purposes:

 

1.The first one is for new feature
2. The second one is for the Small fixes that aren’t related to the feature.
Instead of committing everything together, it’s better to add only the files that are relevant to each task. You can do this by using the command git add <filename> or git add <folder_path>, which lets you push specific files or folders.
 
Once you’ve added the files that are related to your first task, commit them. Then you can repeat the process for the next set of changes.

 

How to Add Part of a File

Sometimes, you might be making multiple changes within the same file, and you don’t want to commit everything at once. In this case, you can use the command git add -i, which allows you to interactively select exactly changes within a file you want to push for commit. This is especially useful when working on two different tasks in the same file.

 

A Quick Tip: Combining Add and Commit

If you’re certain that you want to commit all changes in the current directory, you can skip the separate git add step and combine both the adding and committing into one command. Simply use:
 
git commit -am "<commit_message>"
This will automatically stage any modified files and commit them in one go. Just be careful, as this could include unwanted changes if you’re not paying attention.

 

We can verify by git status command:
 
git status