Search code examples
gitdirectorysubdirectory

Remove folder but not the files within it


How can I remove a folder but keep the files within it with Git?

For example, let’s say I have a folder called ‘MyFolder’ under my repository folder (RepoFolder/MyFolder) and inside ‘MyFolder’ I have files ‘file1’ and ‘file2’ (RepoFolder/MyFolder/file1 file2)

I just want to remove the ‘MyFolder’ folder and keep files ‘file1’ and ‘file2’ under ‘RepoFolder’


Solution

  • The comments have what's probably the answer you want:

    git mv MyFolder/* .
    

    followed by removal of the now-empty folder.

    Be aware, however, that you are, in part, manipulating files and folders in your work-tree. Git does not store what's in your work-tree; rather, Git stores what you have told Git to copy to Git's index.

    This is what running git add all the time is about: every git add you run tells Git: copy this to the index. You can't work directly on files that are in the index: they're in a special Git-only form. You need copies that you can work with. Git puts those in your work-tree. But Git makes new commits from the index, not from your work-tree.

    Files in the index—and in Git—aren't in folders. They just have long names with slashes. That is, in the index, you currently have MyFolder/file1—that's a file, there's no folder, it's just a file named MyFolder/file1—and MyFolder/file2. If you make a commit now, the commit will have those files, with those long names, as well.

    If and when you tell Git to extract some commit, and in that commit, there is a file named super/calli/fragial/istic/expi/ali/docious, Git may have to tell your computer to make folders super (in .), calli (in super), and so on, so as to put in a file named docious. Git understands that your computer demands that files go into folders, rather than just having long names. Git will make these folders as needed. But Git never stored the folders! It just stored a file with the long name.

    In any case, if you use git mv MyFolder/file1 file1 to rename MyFolder/file to file1, so that your computer moves the file out of the folder, Git now has the name file1 in Git's index, and you have the file named file1 in your work-tree. Repeat for file2 and now presumably MyFolder is empty. If Git has, in Git's index, no files whose name starts with MyFolder/, Git won't make directory MyFolder in your work-tree any more. But Git won't remove it either: you must do that yourself.

    (Since Git's index does have files named file1 and file2 in it, the next commit you make will contain files by that name. The current commit continues to have MyFolder/file1 and MyFolder/file2 in it. If, in the future, you go back and extract this commit into your work-tree, Git will create MyFolder/ if it has to.)