If the folder structure is:

├── file1.rtf
├── file2.rtf
... #there are many more files.
├── moreFiles.rtf
├── subFolder1
├── subFolder2
├── subFolder3
... #there are many more subfolders.
└── moreSubFolders

How would I delete all subfolders except subFolder1 without deleting any of the files?

I do not want to have to name each folder which should be deleted.

I also do not want to have name each file which should not be deleted.

I want a command that only deletes folders, not files, and allows the user to exclude some folders from being deleted.

  • Welcome to Ask Different :) Unless I am interpreting the question incorrectly, what's wrong with running rm -rf parentFolder/subFolder1? – Nimesh Neema Aug 20 '20 at 22:50
  • Just to rephrase the question to make it clearer, are you trying to delete jsut the empty subfolders? – Allan Aug 21 '20 at 0:03
  • @NimeshNeema I should have been more clear that there are MANY (twenty or so) subfolders. Updated. – Jack Aug 21 '20 at 5:36
  • @Allan whether the subfolder is empty or not does not matter. I'm just trying to delete some of the subfolders – Jack Aug 21 '20 at 5:37
  • Perhaps you can approach the problem by considering copying/moving files rather than deleting, which can be problematic if files get deleted by accident. – IconDaemon Aug 21 '20 at 15:13

Rule-based deletions tend to be tricky and can easily go wrong. In your case the following might work

find "parentFolder" -depth 1 -type d ! -name subFolder1 -ok rm -r -- '{}' \;


  • only looks one level beneath parentFolder (-depth 1)
  • only looks at directories (-type d)
  • skips subFolder1 (! -name subFolder1)
  • prompts for the deletion of any non-skipped directories (-ok rm -r -- '{}' \;)

PS: To skip several directories use ! \( -name subFolder1 -o -name subFolder2 \), to delete without prompting use -exec rm -r -- '{}' +.

  • might need to escape the ! as \! – TJ Luoma Aug 21 '20 at 16:19
  • @TJLuoma Bash at least doesn‘t complain – nohillside Aug 21 '20 at 16:28
  • I think it has something to do with globbing -- and I think there's a setting for zsh which would make it not complain. Anyway, if someone reads this in the future and it doesn't work, try putting a \ in front of the ! – TJ Luoma Aug 24 '20 at 6:18
  • @TJLuoma In zsh it's probably possible without find :-). In bash one can use !(pattern-list) to exclude patterns, ! also starts history substitution unless followed by a space (so a lonesome ! usually is ok). – nohillside Aug 24 '20 at 6:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .