Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add new folder to git branch without adding it to master

Tags:

git

git-branch

How does one add a new folder to a branch in git without having that folder show up in the master branch?

e.g. 
git branch myNewBranch
git checkout myNewBranch
mkdir foo

git checkout master
ls

the myNewBranch directory is also added to master

like image 315
binarygiant Avatar asked Dec 02 '22 22:12

binarygiant


2 Answers

Just because you created the folder git will not automatically start version controlling it. The folder you created is unknown to git so git will not touch it.

git init #create repo
touch file1.txt
git add file1.txt
git commit -m 'initial commit'
git branch newBranch
git checkout newBranch
mkdir folder
touch folder/file2.txt
git add folder #tell git we want to track the folder
git commit -m 'second commit'
git checkout master
# folder/file2.txt is not available as expected.

Edit: To clarify the folder in your example was not added to master, it actually was not added to any branch.

like image 170
Alex Ionescu Avatar answered Dec 11 '22 16:12

Alex Ionescu


It would seem you have 2 misconceptions that are confusing you.

  1. Git does not overwrite unstaged changes when you switch branches. You need to add and commit a file before Git will do anything to that file (like modify or remove it when you checkout a different branch).
  2. Git does not track directories, it only tracks files. You cannot version an empty directory in Git. If you want to commit an empty directory to Git, the conventional workaround is to add an empty .gitignore in that directory and commit that.
like image 40
Peter Lundgren Avatar answered Dec 11 '22 16:12

Peter Lundgren