Is there a command to remove all files and subdirectories in a directory without deleting the directory?
For example if I have directory dontDeleteMe
with subdirectories 1
, 2
, 3
and each subdirectory has a few pictures in it, how can I remove the subdirectories 1
, 2
, and 3
and all the files in the them, without removing the parent directory dontDeleteMe
?
To remove everything in a directory without removing the directory, type in:
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:
Another one would be to use
find
's-exec
option or pipe toxargs
(below):Open terminal (Ctrl+Alt+T) ant type this:
This will match all files and directories within
somedir
and its (grand-)children including "hidden" dot files but excludingsomedir
itself because of-mindepth 1
, then-delete
them.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: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:Use
xdev
option to delete files only within device boundary.To delete (in terminal) all files and subdirectories except for the base directory named "dontdelete":
You can use
find
with the-delete
flag:The
/*
is important as it tellsfind
to search only INSIDE the folder called "dontDeleteMe".Also ensure that the
-delete
flag is at the end of thefind
command.What says:
Remove all files starting with . in "directory" and all other files too.
Though as kindly noted by Neftas this solution is not safe!
Safer solution is:
There is an even simpler answer:
cd dontDeleteMe
rm -rf *
Basic system administration lecture time: Be sure to pay attention to where you are when you use sweeping commands like this.
I can't say that enough. I've had to recover a box because someone wasn't paying attention and typed in
rm -rf *
while in /.*nix assumes that if you are root or if you are sudo-ing as root that you know what you are doing. So make sure that you know what you're doing before you do it.
An alternative which makes sure your 'cd' command works before you issue the 'rm' is to use
I am not sure why this is so complex, help me if i am wrong
That's it