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?
3 Answers
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.
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? Jul 26, 2016 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 * {} \;
– user172564Jul 26, 2016 at 16:55 -
Thanks, that works, but I am still getting the message. Am I just being too picky? Jul 26, 2016 at 16:59
-
-
@requiemforameme No mate not at all. I updated my answer, just do that and that won't show you any error.– user172564Jul 26, 2016 at 17:02
find somedir -type f -exec rm {} \;