For this type of dir structure :


I know that I can use rm -rf <<folderPath>> to delete parent folder and all sub-folders, but I want to delete all folders and files except \\\rdwlhsdevserver\root\Childfolder

After running cmd, output should be like:


2 Answers 2

rm -rf /path/to/root/*/*

NOTE: Please test this first by making a similar test directory structure. Your shell may not support this kind of syntax (I tested on bash and zsh).

  • 1
    In bash, that ** is the same as * unless you turn on the globstar option to enable zsh-style recursive globbing. But anyway, here, you'd want */*, not **/*. You'd also need to tell the shell to remove hidden files (add (D) in zsh or turn on the dotglob option in bash). Aug 31, 2016 at 7:37
  • 1
    Good points. And with globstar on, bash will actually delete the children of root with **/*. zsh will do the same. I am going to update the answer. Aug 31, 2016 at 7:57

With GNU or BSD find:

find /path/to/root -mindepth 2 -delete

With zsh:

rm -rf /path/to/root/*/*(D)

However note that if there are symlinks to directories in /path/to/root, they will be followed to remove the files in them. You may also run into a Arg list too big error which you could work around by enabling the rm builtin:

zmodload zsh/files
rm -rf /path/to/root/*/.(D)

(the builtin version of rm can remove .)

If you don't want to follow symlinks:

zmodload zsh/files
dirs=(/path/to/root/*(D/)) && rm -rf $^dirs/.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.