Linux delete all directories in directory

How do I remove all sub-directories from within a directory?

This question is kind of a phase II to the first question I posted at here I have a directory that contains a bunch of sub-directories, .zip files, and other random files not contained within a sub-directory. I’d like a command line script to remove all sub-directories from within the parent directory, but keep all zip files and loose files that don’t belong to any sub-directories. All of the sub-directories have content, so I believe I’d need to force their deletion with the -f command. So basically, a command that looks inside the parent directory (or the current directory), deletes all folders from within it, but keeps all other content and files that are not a folder or contained within a folder. I understand that deleting items from the command line requires special care, but I have already taken all necessary precautions to back up remotely.

6 Answers 6

In BASH you can use the trailing slash (I think it should work in any POSIX shell):

Note the — which separates options from arguments and allows one to remove entries starting with a hyphen — otherwise after expansion by the shell the entry name would be interpreted as an option by rm (the same holds for many other command line utilities).

Add the -f option if you don’t want to be prompted for confirmation when deleting non-writeable files.

Note that by default, hidden directories (those whose name starts with . ) will be left alone.

An important caveat: the expansion of */ will also include symlinks that eventually resolve to files of type directory. And depending on the rm implementation, rm -R — thelink/ will either just delete the symlink, or (in most of them) delete the content of the linked directory recursively but not that directory itself nor the symlink.

If using zsh , a better approach would be to use a glob qualifier to select files of type directory only:

rm -R -- *(/) # or *(D/) to include hidden ones 

to include symlinks to directories (but because, this time, the expansion doesn’t have trailing / s, it’s the symlink only that is removed with all rm implementations).

With bash , AT&T ksh , yash or zsh you can do:

Beautiful! This works perfectly. I didn’t realize it was so easy to do. Would you mind elaborating on the -r vs. -R and what those commands do? Many thanks.

Just be careful not to change the order of the * and the /. rm -R — /* does something totally different that you may not want to happen 😐

In addition to the wildcard way, you can also use find (at least GNU find) to do this:

find -mindepth 1 -maxdepth 1 -type d -print0 | xargs -r0 rm -R 

As with other find lines, you can run the first part ( find -mindepth 1 -maxdepth 1 -type d ) to see a list of directories that will be removed.

Читайте также:  Открывать exe файлы linux

Portably (POSIXly), you’d use the -exec cmd <> + syntax instead of -print0 | xargs -r0 , and -prune do limit the depth:

find . ! -name . -prune -type d -exec echo rm -R <> + 

(and remove the echo to actually do it).

A safer option (here also assuming GNU mv ) is to do something like this:

find -mindepth 1 -maxdepth 1 -type d -print0 | xargs -r0 mv -i -t ../to-rm # or (but beware of symlinks!) mv -i -t ../to-rm -- */ # or mv -i -- */ ../to-rm 

any of which will move all the stuff into ../to-rm instead of deleting it. You can verify it did what you wanted, them rm -Rf that directory at your leisure.

+1 for the «CLI-Trash bin» to-rm and find which nicely handles directories beginning with a dot (in addition to any other cumbersome escaping). 🙂

Thanks for the tip. I like the idea of moving to a separate directory before deleting. I’m working via Terminal on Mac OS X, and I believe I’d need to install some kind of GNU package to use the -mindepth and -maxdepth commands, correct?

@Evster not sure if Mac OS X find supports those. I’d guess fink (is that still around?) could install a find that does. Or you could omit them, and then filter the produced file list using grep. Definitely use the mv option on that, istead of rm.

You might want to create a script for some of these suggestions, especially rm -R — */ , and keep it in your /usr/local/bin folder; or create an alias in your ~/.bashrc file. Since it’s so easy to mistype a command and break your system — even a single letter and/or the order of letters can result in catastrophic consequences — this would serve as a somewhat more robust solution than having to type the different options and arguments each time you want to accomplish this task.

Also, you may want to include the -i or —interactive=once or -I or —interactive=always option to your script/command which will serve as another tool to avoid the unintended deletions.

Furthermore, something like derobert suggested would be best; just copy/paste the script into a file/terminal-editor and adjust it to your specific needs, and the files/directories will be moved into a single directory (the contents of which you can check/verify) that you can simply remove by issuing the rm -rf command.

Another option is to use a GUI-application, such as your file manager, and simply select all applicable files/folders you want to delete. Check your distribution’s manual-pages if you don’t have permissions.

Finally, if the folders are empty — essentially simple filenames — you can use the rmdir command to delete them. It doesn’t work for everything you may want to delete, but it will come in handy at times when you want to do some «house-cleaning». **You may want try the -p —ignore-fail-on-non-empty option, which will allow you to delete certain sub-directories as well as their empty «parents»—the directories in which they reside.

Источник

How do I remove a directory and all its contents?

The following command will do it for you. Use caution though if this isn’t your intention as this also removes files in the directory and subdirectories.

Читайте также:  What is linux virtual server

«-f» is «—force» which overrides some sanity checks and prompting. A safer command to start with would be rm -r directoryname .

@JimParis I think the word «safer» is relative. Suppose you are writing a script to run on a remote computer. That script has a command which is supposed to remove a directory. Here, it would be «safer» to use rm -rf directoryname coz you wouldn’t want your script to pause execution, because it’s waiting for user input. Of course, you have to be sure that deleting the directory would do no harm.

if rm -rf directoryname fails you, try using rm -R -f directoryname , or rm —recursive -f directoryname .

If you are not having any luck with these, you should consider reinstalling rm or switching shells.

These were the options available on my rm man page, I looked it up by typing man rm to view my options on recursive deletion and the force options.

Does your rm man page list -r ? What does it do? (Try it in a directory that you create just for testing purposes, with only dummy files (and maybe subdirectories) in it.) What operating system are you using?

P.S. If rm -r doesn’t work, that would be an OS issue, not a shell issue. (Strictly speaking, it would be an issue with the version of rm that you’re using, so you could address it by installing a different version of rm , or searching your system to see whether you already have a different version of rm in some directory other than /bin .)

Ah, right. I forgot to mention I’m on Ubuntu 14.04 When I ran man rm in my terminal, it gave me a text file with the less text viewer. I scrolled found an indented entry with a whole that had the -R and —recursive options cozied up with the -r option, signifying that all of those arguments are identical.

edit: have you tried sudo rm -r directoryName ? The unwritten rules of the basic commands is that -r will allow a program to run recursively on every file your filesystem (starting where ever you choose!) and that -f will forcefully do things, even if it’s dangerous. ‘cd’, ‘mv’, ‘ls’ mostly holds this principle true. ls -r / is gonna be a duzie, and cp -rf / /dev/null will destroy everything on your filesystem.

Other answers show how to completely remove a directory’s content, but IMO they don’t address the literal question of the original post — that is, how can one delete subdirectories (as opposed to usual files). In other words, how can one delete empty directory structures while keeping subdirectories containing files ?

This can be achieved with find :

find directoryname -type d -delete 

This command will recursively search for directories ( -type d ) through directoryname and -delete them only if their subdirectories or themselves don’t contain any files.

Источник

Removing almost all directories and files in linux

Quick question : I want to delete all but 1 file and 1 directory from the directory I am currently in. How do I do this? The case scenario : I have a directory which has three directories a b c and three files 1.php 2.php 3.php. I want to remove directories a,b and files 1.php and 2.php ONLY! I am having a hard time trying to do this. The solution should scale up, i.e. I don’t want to have to list all the files I do want to delete, only the ones that should stay. What do I do?

Читайте также:  Операционная система windows операционные системы unix linux

to delete a folder use rm -rf folder question is a bit unclear about how the structure looks like, perhaps post the output of ls -R

This question would be better on superuser.com or askubuntu.com, as it is not about programming. (I voted for migration.) If you actually want to write a program which does this, please edit your question accordingly.

@Fredrik : Thank you. The question is how do I delete all but one directory and one file from a directory i am currently in?

@Paulo : Oops! I was debating whether I post it here or on superuser. Then got carried away by similar questions asked here and also because stackoverflow allowed me to tag the post with Linux and Ubuntu tags 🙂

3 Answers 3

shopt -s extglob echo rm -r !(3.php|c) 
$ mkdir -p x/a x/b x/c $ cd x $ touch .php $ ls -F 1.php 2.php 3.php a/ b/ c/ $ shopt -s extglob $ echo rm -r !(3.php|c) rm -r 1.php 2.php a b 

Beat me to it. Setting shopt -s extglob makes it easy. Wonder why it isn’t on by default as it is in Kornshell?

Thanks Arafinwe. How does that solution scale up when I have 20 directories and 30 files, and I want to delete all but 1 directory. Its going to be tough to mention every single dir name and file name that way, and do the rm operation. Assume that I will need to recursively delete the directories.

For deleting all but one file in a general case, it gets more complicated.

Here is a solution in bash (or other shells, I did not check on which ones it works):

function deleteAllBut() < local pattern="^($1)" for p in "$" do pattern="$pattern|($p)" done pattern=$pattern\$ for f in * do [[ $f ~= $pattern ]] || echo $f done > 

to list all local files but these two ones. (This will not delete hidden files, e.g. ones whose names start with a . .)

How does it work? It first builds a regular expression from the command line arguments (which beforehand were expanded by the shell), then iterates through all files in the current directory and echoes all ones that do not match the pattern.

Change the echo $f to rm -r $f to actually delete those files and directories.

The following is the original answer for the original question.

cd rmdir a b rm 1.php 2.php 

This assumes your directories are empty. If they are not (and you want to remove the contents, too), use

instead of the second line above. ( -r stands for recursive.)

Of course, you then can combine the last two lines:

or, if you want to be tricky:

Источник

Оцените статью
Adblock
detector