Remove all files except the subdirectory(without pattern) in a directory

I used rm * and it deleted the files in the directory but gives and error message for unsuccessful subdirectory deletion.

"rm: cannot remove 'DirectoryName': Is a directory"

I dont want to explicitly get the above error.

What are the modifications I have to do in the rm command?

rm -rf *

Be very very careful on what you are deleting. This command deletes everything under the current dir.

1 Like

I've had problems with the suggested rm -r because it will follow symbolic links out to other filesystems. Imagine what fun we had when we ran that from /opt/BOB/new only to find that there was a link to /usr/lib contained within it. Yes, it went off an cleared that too. Good thing we didn't have a link to /dev, /usr or /.

If you have few enough files, you could:-

for object in *
do
   if [ -f $object ]
   then
      rm $object
   fi
done

This tests that the item is a file. It will not traverse down directories though. Do you want to do that too, or does the above suffice?

If you have lots of files, then you may have to write a stronger loop. We can get to that if you need it.

Robin
Liverpool/Blackburn
UK

2 Likes

Hopefully you cannot replicate that with anything relatively current. If so, you should report it.

It's been nearly ten years since POSIX explicitly addressed symlinks during directory traversal. Released in 2004, the Issue 6 rm manual requires:

Rationale for the inclusion of that clarification follows later on:

Regards,
Alister

1 Like