Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all files but keep all directories in a bash script?

Tags:

I'm trying to do something which is probably very simple, I have a directory structure such as:

dir/     subdir1/     subdir2/         file1         file2         subsubdir1/             file3 

I would like to run a command in a bash script that will delete all files recursively from dir on down, but leave all directories. Ie:

dir/     subdir1/     subdir2/         subsubdir1 

What would be a suitable command for this?

like image 739
Grundlefleck Avatar asked Aug 14 '09 21:08

Grundlefleck


People also ask

How do you delete all files in a directory without deleting the directory?

Open the terminal application. To delete everything in a directory run: rm /path/to/dir/* To remove all sub-directories and files: rm -r /path/to/dir/*

How do I delete all files and subdirectories in a directory in Linux?

To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r . Directories that are removed with the rmdir command cannot be recovered, nor can directories and their contents removed with the rm -r command.


1 Answers

find dir -type f -print0 | xargs -0 rm 

find lists all files that match certain expression in a given directory, recursively. -type f matches regular files. -print0 is for printing out names using \0 as delimiter (as any other character, including \n, might be in a path name). xargs is for gathering the file names from standard input and putting them as a parameters. -0 is to make sure xargs will understand the \0 delimiter.

xargs is wise enough to call rm multiple times if the parameter list would get too big. So it is much better than trying to call sth. like rm $((find ...). Also it much faster than calling rm for each file by itself, like find ... -exec rm \{\}.

like image 150
liori Avatar answered Oct 19 '22 04:10

liori