When I make changes to a file in Git, how can I commit only some of the changes? For example, how could I commit only 15 lines out of 30 lines that have been changed in a file?

 

In Git, you can commit only some of the changes within a file using a feature called "partial staging" or "selective staging." This allows you to choose specific lines or chunks of code to include in a commit while leaving other changes in the same file unstaged. Here's how you can do it with an example:

Let's say you have a file called example.txt with 30 lines, and you want to commit only 15 of those lines.

  1. Make changes to the file:

    Edit example.txt and make the necessary changes. In this example, let's say you've edited lines 10 to 25.

  2. Check the status of your changes:

    Run the following command to see the status of your changes:

    bash
  • git status

    You'll see that example.txt has been modified, but the changes haven't been staged yet.

  • Stage the specific lines you want to commit:

    To stage only lines 10 to 25, you can use the git add -p command, which allows you to interactively stage changes:

    bash
  • git add -p example.txt

    Git will show you a series of prompts for each "hunk" of changes (a hunk is a contiguous section of code). You can choose which hunks to stage or leave unstaged.

    • To stage a hunk, type y.
    • To skip a hunk, type n.

    In your case, you would select y for the hunks corresponding to lines 10 to 25.

  • Verify the staging:

    Run git status again to ensure that only the selected lines have been staged for commit.

  • Commit the staged changes:

    Now, you can commit the staged changes:

    bash
    1. git commit -m "Committing only lines 10 to 25 from example.txt"

      This will create a commit with only the selected lines.

    By using the git add -p command, you can selectively stage and commit specific lines or changes from a file while leaving other changes in the same file unstaged. This gives you fine-grained control over what gets included in your commits.

    Comments