How to revert a single file from Git Repo


Let's say we have a git repo named myrepo and we have 4 files in it.

% ls -l

-rw-r--r--  1 c2ctechtv  staff  0 Aug 15 13:07 script1.sh
-rw-r--r--  1 c2ctechtv  staff  0 Aug 15 13:08 script2.sh
-rw-r--r--  1 c2ctechtv  staff  0 Aug 15 13:08 script3.sh
-rw-r--r--  1 c2ctechtv  staff  0 Aug 15 13:11 script4.sh

Now let us take a look at the commits.

% git log --oneline 

a7b6be2 (HEAD -> main) added script4
e338436 added two files
6c9e0b7 initial commit

So we have 3 commits.

Now I want to revert just one file which is script2.sh

Steps to revert a single file from Git Repo

    Step 1: Identify the commit hash for the file

    In our case it is e338436.


    Step 2: Revert the File:

    git checkout e338436 -- script2.sh
    Revert a Single File from Git Example

    You can review the changes using git status command.


    Step 3: Commit the Reverted Changes::

    git add script2.sh
    git commit -m "Revert script2.sh to previous state"

    Step 4: Pust changes to Origin:

    Finally we push the changes to Origin Server (GitHub/BitBucket/GitLab)

    git push origin main

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap