How to Delete All the Files in a Directory

On Linux and Unix servers, you can use the “rm” command to delete one file, multiple files, or an entire directory. But what do you do if you want to preserve the directory but delete all the files in it? On a dedicated server, such a feature would be particularly useful if, for example, you wanted to delete the log files in a log directory but keep the directory, or delete the files in a mail queue but keep the queue directory.

Normally, when you delete a directory and all its contents, you would use this command:

rm -r directoryname

If your directory has several files in it that you want to delete but wish to keep the directory itself, you can run one of the following commands:

cd directoryname
rm *


rm directoryname/*

This works for a single directory, but if you have subdirectories within “directoryname”, those will be deleted as well with the “rm” command. The folks at nixCraft suggest using “find” to work around this dilemma. Type this command:

find directoryname/ -type f -delete

Any files found anywhere within the directory structure under “directoryname” will be found and deleted, preserving the directory and all of its subdirectories. Since these commands can easily remove multiple files in multiple places, you need to make absolutely sure you want to delete everything within a directory before you do it. While it might be possible to recover files that you accidentally delete, nothing is guaranteed.