Let us suppose I want to make sure that there will be a folder called foo and a file inside it called bar. After I have made sure foo/bar exists I do not intend to version it, therefore I add it to .gitignore.
As the commenters have noted, if you add a file-path to a
.gitignore file after the file is committed, it's too late.
You have two different questions combined into one, here:
How do I convince Git to create an empty directory? (This is your practical problem, the one you need to solve for what you're doing.)
.gitignore actually work? What rule(s) apply what actions and when? (This is what you are asking in your subject line.)
For item 1, see How can I add an empty directory to a Git repository?
For item 2, see https://git-scm.com/docs/gitignore. Let me extract this sentence from there and put it in bold, though: Files already tracked by Git are not affected. If you've
git add-ed a path that would be ignored, it is not ignored. To get it to become ignored, you must explicitly remove it, which has its own pitfalls. See Stop tracking and ignore changes to a file in Git and How to make Git "forget" about a file that was tracked but is now in .gitignore?
Note that when dealing with accidentally tracked configurations, that cannot now be removed, via
git update-index, the modern recommendation is