Checkout without deleting local files

Assuming I have a repository with two braches: main and dev

On branch main i have the following files: myFile1, myFile2, and MyFile3 - let’s assume myFile 2 is a configuration file wich I must have locally, but don’t need to have it on dev branch.

(I need to have this file on branch main, because the server deploys from it)

On branch dev I have only: myFile1 and myFile3.

When I run ‘git checkout main’, the 3 files are added to my local folder, so I want to change to the dev branch. But, when i run ‘git checkout dev’, the file myFile2 is removed from the local folder, since it’s not on dev branch. I have myFile2 at .gitignore, but, idk why, it’s not being ignored.

Can someone help me, please?

1 Like

A file that is part of the current commit (as it is when you check out main) is never ignored, so that is expected behavior.

I assume that myFile2 is some sort of configuration file, and you want to use different configurations for deployment and local testing? In that case it’s probably best to add some way to use a different configuration without changing the configuration file your server uses, exactly how depends on the structure of your application.

In any case, if you want to see myFile2 from the dev branch you can always check it out — i.e. from within the dev branch type:

$ git checkout main -- myFile2

This will checkout that single file from main and bring it into the dev branch, where it should be ignored by Git, if I’ve understood correctly.

As @airtower-luna mentioned, .gitignore rules don’ apply to files which are already part of a commit, but only to new files introduced in the work area. You can always bypass .gitignore rules manually, e.g. by force adding and committing a file that is ignored.

Personally, I’d just have a second clone in a sibling folder. That’s the easiest thing for me to reason through.

You can do that w/:

git clone origin-url local-clone-directory

… There are lots of fancier ways to address your problem.

With this approach, you have one repository that tracks main (repo-main) and one that tracks dev (repo-dev). And when you need a file from main, you update repo-main and copy it into repo-dev.

Using two separate repositories means you have to update them separately, possibly between them, too. Using git worktree might be the more elegant solution. It basically lets you create a second (or more) working tree and staging area from the same repository.

Yes, I’m aware, but I don’t believe the complexity is worth it. Disk space is cheap and learning an extra command is expensive.

The disk space is cheap, but things getting messed up because having two separate repositories is confusing isn’t. And you don’t really need to learn another command, you just need to look up how to do it once, and then both worktrees work as usual. :slightly_smiling_face: