In a scenario where you are working with an application which files contain some sensitive data, you most likely don’t want to push code to a remote repository. The best practice, in that case, is to remove the file from the git. You are in the right place In case that you want to keep the file locally. In this tutorial, you will learn how to git remove files but keep the local versions.

Advertisement

Git Remove File – Keep Local Version

  • In a situation where the file hasn’t been committed or pushed to a remote repository, use the command below.
    git reset {fileName} 
    
  • If the file has already been committed or pushed to a remote repository, tracking for it can be removed. In that case, your command will look like this.
    git rm --cached {fileName} 
    

Git Remove Directory – Keep Local Version

What about the directory removal? You’ll use pretty much the same syntax. The only difference is that you will append it with the -r option. Here’s an example

git rm --cached -r {directoryName} 

Keep in mind that in both cases terms within brackets have to be changed with the actual file or directory name that you want to remove.

Now here’s one useful trick. Even though you removed the file or directory with the commands above, Git will still try to track it. Additionally, if you accidentally commit or push that certain file or directory in the future, it will end up in a remote repository again. To avoid that, add the full path to the file/dir in question to the .gitignore file. That way you’ll make sure that it won’t end up in the remote repo again one way or another.

And we’ll wrap up this tutorial with that information. Put what you learned about git remove file but keep local to good use when you are dealing with sensitive information in your repositories. Security and data sensitivity are both very important!

Share.

Leave A Reply