Operating System - HP-UX
1760034 Members
3755 Online
108889 Solutions
New Discussion юеВ

Remove contents of directory but not the directory itself

 
SOLVED
Go to solution
Ed Hon
Regular Advisor

Remove contents of directory but not the directory itself

Is there a easy way of removing recursively all the files and subdirectories in a directory without removing the directory itself? For example, I want empty out everything in /dir without removing /dir itself. Thanks.
11 REPLIES 11
Ken Hubnik_2
Honored Contributor

Re: Remove contents of directory but not the directory itself

cd to /dir
rm -rf *
Tom Jackson
Valued Contributor

Re: Remove contents of directory but not the directory itself

Hi Ed:

rm /dir/*

You can use the -i option to confirm deletes.

Tom
Shannon Petry
Honored Contributor

Re: Remove contents of directory but not the directory itself

For hidden files you will also need to remove the dot files.
I.E.
% rm /dir/.??*

or
% cd /dir
% rm -rf .??*

Notice that there are two place holders to ensure that neither "." nor ".." are removed, as that is the current and parent directories.

Regards,
Shannon
Microsoft. When do you want a virus today?
Armin Feller
Honored Contributor

Re: Remove contents of directory but not the directory itself

# cd /dir
# rm -rf *

Regards ...
Armin
RAC_1
Honored Contributor

Re: Remove contents of directory but not the directory itself

cd /dir
rm -fr *
There is no substitute to HARDWORK
Paul Sperry
Honored Contributor

Re: Remove contents of directory but not the directory itself

cd /dir
rm -fr *
James R. Ferguson
Acclaimed Contributor
Solution

Re: Remove contents of directory but not the directory itself

Hi Ed:

While:

# cd /dir
# rm /dir/*

...will accomplish what you seek in most cases, the shell's expansion of "*" may exceed ARG_MAX (see '/usr/include/limits.h').

To circumvent this, you could do:

# cd /dir
# find . \( -type d -a ! -name . \) -print|xargs rm -rf

Note that the current directory (".") is excluded.

Regards!

...JRF...

Jochen Heuer
Respected Contributor

Re: Remove contents of directory but not the directory itself

A little easier:

$ cd /dir; rm -rf `ls -A`
Well, yeah ... I suppose there's no point in getting greedy, is there?
James R. Ferguson
Acclaimed Contributor

Re: Remove contents of directory but not the directory itself

Hi (again) Ed:

Sorry, I dropped part:

# find . \( -type f -o \( -type d -a ! -name . \) \) -print|xargs rm -rf

Regards!

...JRF...