How to remove a directory without removing its content?

Let's say that I have a directory /home/smit/test. Inside it I have many subdirectories and files. I want to remove only the Directory /home/smit/test and not its inner content, So that files and subdirectories of /home/smit/test will automatically be included in /home/smit/?

Also, in a real case I have /usr/share/backgrounds/all/ directory which has many subdirectories. and theses sub directories have lots of images. I want to remove all subdirectories So that their contents will be included in /usr/share/backgrounds/all/. I can do this with GUI but I want to do it with cool way by terminal. How can I do it?


Solution 1:

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.