Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git remove a file from a branch, keep it in the master

Tags:

I create a new branch

git checkout -b mybranch

then I delete a file from it

git rm --cached myfile.txt

but I want to keep it in the master; why when I checkout to the master

git checkout master

I get an "error: The following untracked working tree files would be overwritten by checkout: file.txt" and if I force the checkout

git checkout master -f

the file is deleted from the file system?

I am sure I am missing something, but I just wanted to remove the file from a branch and not from the master while it seems that git wants to merge the branch when I checkout master.

The reason why I used git rm and not gitignore was that the file was already been committed.

like image 364
Eugenio Avatar asked May 24 '16 19:05

Eugenio


People also ask

How do I remove a file from git without deleting it?

Using the git rm –cached Command We've mentioned that git rm FILE will remove files from the index and local working tree by default. However, the git rm command provides the –cached option to allow us only to remove files from the repository's index and keep the local file untouched.

How do I delete something from a branch?

git branch is the command to delete a branch locally. -d is a flag, an option to the command, and it's an alias for --delete . It denotes that you want to delete something, as the name suggests. - local_branch_name is the name of the branch you want to delete.


1 Answers

If you want to keep tracking myfile.txt on master but deleted from mybranch, then you simply need to delete it and commit the delete.

git checkout -b mybranch
rm myfile.txt
git commit -am "delete myfile.txt"

Now when you checkout master, you'll see your file returned and when you checkout mybranch it will be gone again.

Note that if you merge mybranch into master, it will be deleted on master then too.

like image 98
Jeff Puckett Avatar answered Sep 22 '22 00:09

Jeff Puckett