How to remove all files and subdirectories in a directory WITHOUT deleting the directory in bash?
To remove everything in a directory without removing the directory, type in:
rm -rfv dontDeleteMe/*
Please note, the /*
part is very important. If you put a space before the *
, it will delete all your files in your current directory.
Also, be very careful playing with rm
, -r
and *
all in the same command. They can be a disastrous combination.
Update: Okay, I realized if you do have hidden/dot files [filenames with dots at the beginning, e.x. .hidden
] then this will leave those files intact.
So really, the simplest solution to the original question is:
rm -rfv dontDeleteMe && mkdir dontDeleteMe
Another one would be to use find
's -exec
option or pipe to xargs
(below):
find dontDeleteMe/* -print0 | xargs -0 rm -rv
The only reason rm -r ./*
do not always work is because you can have hidden files and/or folder that are not matched by *
.
To this end, bash
provide an option to make *
match everything, even hidden objects:
cd dont-delete-me
shopt -s dotglob
rm -r ./*
It can be useful to reset dotglob
to its default (unset) state, if you keep on using the shell where you executed the above commands:
shopt -u dotglob
Open terminal (Ctrl+Alt+T) ant type this:
find somedir -mindepth 1 -delete
This will match all files and directories within somedir
and its (grand-)children including "hidden" dot files but excluding somedir
itself because of -mindepth 1
, then -delete
them.