Bash – Remove All Files and Subdirectories Without Deleting Directory

bashcommand linedirectoryrm

Is there a command to remove all files and subdirectories in a directory without deleting the directory?

For example if I have directory dontDeleteMe with subdirectories 1, 2, 3 and each subdirectory has a few pictures in it, how can I remove the subdirectories 1, 2, and 3 and all the files in the them, without removing the parent directory dontDeleteMe?

Best Answer

To remove everything in a directory without removing the directory, type in:

rm -rfv dontDeleteMe/*

Please note, the /* part is very important. If you put a space before the *, it will delete all your files in your current directory.

Also, be very careful playing with rm, -r and * all in the same command. They can be a disastrous combination.

Update: Okay, I realized if you do have hidden/dot files [filenames with dots at the beginning, e.x. .hidden] then this will leave those files intact.

So really, the simplest solution to the original question is:

rm -rfv dontDeleteMe && mkdir dontDeleteMe

Another one would be to use find's -exec option or pipe to xargs (below):

find dontDeleteMe/* -print0  | xargs -0  rm -rv