I'm setting up an automation process where I am deleting files in a directory which contains sub-directories. I only want to delete the files in the directory, and want to keep the sub-directories intact. So right now I am just using rm * to delete the files in that directory. However, this command throws the message: cannt remove 'dir': Is a directory. I know I'm being knit-picky, but I don't want that message to repeatedly appear in my logs. Is there a better command I can use for deletion or a way that I can tell rm to ignore the sub-directories?

  • 1
    find somedir -type f -exec rm {} \; – user4556274 Jul 26 '16 at 16:55

You can just throw away the error messages:

rm * 2>/dev/null

That'll throw away all errors. If you want to see other potential errors then we can do something more complicated:

rm * 2>&1 | grep -v 'cannot remove .*: Is a directory'

In this way other errors will still be logged.

  • Question says "want to keep the sub-directories intact"... – Stephen Harris Jul 26 '16 at 17:09

In zsh:

rm *(^/)

Other shells have no equivalent to zsh's glob qualifiers. Instead you can call find, which is capable of discriminating files by type, and tell it not to recurse into subdirectories other than . (the starting directory).

find . -name . -o -type d -prune -o rm -f {} +

This deletes dot files, whereas * doesn't match dot files. If you want to preserve dot files, tell find not to call rm on them.

find . -name . -o -type d -prune -o ! -name '.*' rm -f {} +

(You can use -mindepth, -maxdepth and -delete, but only if you don't need your script to run on systems where find doesn't have these options. The options I used are portable.)


Here you are:

find ./ -type f -exec rm -f * {} \; 2> /dev/null

If you want to keep even files in your subdirectories intact:

rm -f * 2> /dev/null
  • I thought recursive deletes removed all data in sub-directories as well? – requiemforameme Jul 26 '16 at 16:52
  • @requiemforameme Yes it does. Sorry I didn't see you said only files, You should use: find /path -type f -exec rm -f * {} \; – user172564 Jul 26 '16 at 16:55
  • Thanks, that works, but I am still getting the message. Am I just being too picky? – requiemforameme Jul 26 '16 at 16:59
  • Remove the star from FarazX's comment. Or just use -maxdepth 1. – Mikel Jul 26 '16 at 17:02
  • @requiemforameme No mate not at all. I updated my answer, just do that and that won't show you any error. – user172564 Jul 26 '16 at 17:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.