How to Add a File to the Last Commit in Git

John Wachira Feb 15, 2024
  1. Add a File to the Last Commit in Git
  2. Alternative Way to Add a File to the Last Commit in Git
How to Add a File to the Last Commit in Git

This article outlines the process of adding a file to the last commit in Git. This comes in handy when you forgot to include a file in the last commit and do not want to create a new one.

Let’s jump right in.

Add a File to the Last Commit in Git

For easier context, we will simulate a situation where we need to add a file in our last commit.

We will edit some files in our local repository and add a new jyp.php file. This will be the file we leave out when committing the changes.

Here is the commit history:

Git Add File to Last Commit - Commit History

After the commit, let us look at the state of our index.

$ git status

Output:

Git Add File to Last Commit - State of Index

How do we add the jyp.php file to our Commit to add a file commit?

There are two ways you can go about this. Let’s start with a more straightforward one.

First, we will add the left-out file to commit. We will run the following:

$ git add jyp.php

What’s left is adding the file to the last commit, as shown below:

$ git commit --amend --no-edit

The git commit --amend will fix our commit. We use the --no-edit flag to commit without changing the commit message.

Note
It is not recommended to amend public commits or commits that have been pushed to the remote repository. This can mess up your project’s timeline.

Alternative Way to Add a File to the Last Commit in Git

There is an alternative way of doing this, and it involves the git rebase command. For better understanding, let us look at an example.

We will run an interactive rebase to add a file to Commit to add a file in our local repository.

$ git rebase -i HEAD~2

In the text editor, we will replace pick with edit on our Commit to add a file commit. Use :wq to exit the text editor.

Git Add File to Last Commit - Interactive Rebase

We will create a new Load.txt file and add it to our commit while still in rebase mode. Add the file for the commit and run the git commit --amend command, as shown below:

$ git commit --amend --no-edit

To finish the rebase, we will run:

$ git rebase --continue

Git Add File to Last Commit - Successful Rebase and Update

If you must update your remote repository, run the following:

$ git push --force origin <branchname>

In conclusion, Git allows us to add a file to the last commit when needed. Although we have covered two methods, they are similar and will give the same output.

Author: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn

Related Article - Git Commit