≡ Menu

How to delete all files but not directories on Linux?

It is useful to be able to delete all files within a directory and sub-directories, but not delete the directory structure itself. I am not aware of a way to do this using the Linux command rm, except using sophisticated loops in a shell script.

But there is an easier way to do this in a single line command. This is done using the Linux command find. The command find is a very versatile command which has several interesting arguments that you can pass it.

The command find usually works on a directory and all of its sub-directories.

The following command will list all files within a directory and all sub-directories:

find .

If you want to find all directories that have the extension .sql, the following command will work:

find . -name *.sql

If you want to list all files but not directories, use the following command:

find . -type f

Now the same command as above, but with the -delete flag will delete all files but not directories!

find . -type f -delete

Note that this will delete ALL files under the current directory. Use caution while using this command. Also don’t ever run this command on the root directory or your whole system will be wiped out!

Rahul

{ 0 comments… add one }

Leave a Comment