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
In these situations there is a risk of files with the same name being overwritten. As mentioned by @Arronical, you can avoid this using the -b
flag to mv
which causes any identically named files to be differentiated by appending ~
to their names. However, if there are three or more files with the same name, only the first and last will be saved, so check the contents before moving to protect your files.
The first, simple case is easy; we can use a shell glob. However, this won't move hidden files, so if you have any filenames beginning with .
, start by turning on dotglob
shopt -s dotglob
Then you can run:
mv -b /home/smit/test/* /home/smit
rmdir /home/smit/test
Turn off dotglob
if you like (it will return to default anyway when you open a new shell):
shopt -u dotglob
For the second (real) case, we will use find
, which moves hidden files by default:
Make sure you are in the right location first.
cd /usr/share/background/all
find -type f -exec echo mv -vb -- {} . \;
If that looks good, run it without echo
to actually move files
find -type f -exec mv -vb -- {} . \;
Then find the directories
find -type d
If you see what you want to remove:
find -type d -delete
This is safe since it will refuse to remove directories that still have contents.
Best Answer
The simple way:
or
The asterisk (
*
) matches all characters.To get explanations about what is being done, use
rm
with-v
option. To be prompted before every removal, userm
with-i
option:See
man rm
for more info.