On Git, when developers work on large development projects, they make changes from time to time according to their needs. After that, these changes are pushed to the GitHub server. In some situations, it is only required to add particular changes instead of all, including previous ones, to the Git local repository. However, in such cases, Git enables users to commit the desired part of the code files.
This article will explain the process of committing the desired part of a file in Git.
How to Commit Only Part of a File in Git?
To commit the desired part of a file in Git, first, open the Git bash terminal and switch to the local directory. Then, choose the desired file, open, and update it. After that, commit only the newly added changes to the file by executing the “git add -p” command.
Step 1: Redirect to Local Git Repository
First, switch to the local directory by running the “cd” command:
Step 2: View Repository Content
Then, view the list of content of the current repository with the help of the “ls” command:
The below output indicates that only one file exists in the working directory:
Step 3: Open and Modify File
To open a file in the default editor, use the below-stated command:
As a result, the specified file will open up with the text editor. Then, add some content, save the added changes by pressing the “CTRL + S” and close the file:
Step 4: Commit Particular Part of File
To commit only the new content that has been added to the file, run the “git add” command along with the “-p” flag, which represents the patches:
After executing this command, the existing content of the file will be displayed, and an interactive prompt will be opened. It allows you to decide whether you want to add the new changes to the file.
Choose hunks according to your requirements. For instance, we have selected the hunk and pressed “y” to add the new changes:
We have explained the process of committing the desired part of a file in Git.
Conclusion
In order to commit only a part of a file in Git, first, switch to a particular repository. Choose a specific file and make some changes to it. Then, execute the “git add -p” command along with the file name to commit only the new content of the file to the local repository. This article illustrated how to commit a particular part of a file in Git.