Linux how to remove directory and all files

How to remove all files and subdirectories in a directory WITHOUT deleting the directory in bash?

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 ?

12 Answers 12

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:

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 

@justingrif: find dontDeleteMe/* -print0 | xargs -0 rm -rv I believe in most cases this will work, regardless of spaces, and what not. But cd to /tmp/ and make a test directory and try it out. 🙂

Re-making a directory does not equal deleting its contents. e.g. umask directory permission differences, owner differences, etc. enzotib’s answer would solve the issues with your original syntax

This is not a good answer. Using * is dangerous, and won’t work on dotfiles without «dotglob» (see below). rm -rf dontDeleteMe && mkdir dontDeleteMe doesn’t ensure that the dir is re-created with the same permissions/owner(s). Instead, use one of the find dontDeleteMe/ -mindepth 1 -delete variants below.

@NilsToedtmann, with all due respect, I did give fair warning in my answer that the * should be used with care.

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.

@EricP The main difference between find with -mindepth 1 and rm is that the former will keep the directory and only delete its contents. It’s not safer per se, both will delete everything in the directory without confirmation if you have the permissions to do so. But find is more flexible (it has many more options than rm ).

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:

find /dontDeleteMe/ -xdev -depth -mindepth 1 -exec rm -Rf <> \; 

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»:

Читайте также:  All in one linux home server

You can use find with the -delete flag:

The /* is important as it tells find to search only INSIDE the folder called «dontDeleteMe».

Also ensure that the -delete flag is at the end of the find command.

This solution doesn’t delete any hidden files, unless you enable dotglob . Otherwise, using the -mindepth 1 flag option seems the only way to get it working.

Remove all files starting with . in «directory» and all other files too.

Though as kindly noted by Neftas this solution is not safe!

This command could potentially be dangerous, since you’re also including . and .. directories. This may be avoided by changing <.*>to <. *>, but then you won’t delete hidden files with only one character, such as .a .

There is an even simpler answer:

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

Actually it’s not any more or any less dangerous than what you suggest. All the && does is to chain the two commands together so that they execute at the same time. If anything my method is actually SAFER since you have to stop and .look before you execute the rm -rf *. Pausing to double check is always better.

@user30619 The && operator doesn’t just chain the commands together; it requires that each command be successful before the next one will be executed. If the cd command fails for any reason (directory doesn’t exist, privileges, etc) then the rm command won’t be executed. I’d call that safer.

I am not sure why this is so complex, help me if i am wrong

This has the slight flaw of trying to delete the current directory as well, which, of course, doesn’t work, because it’s still in use as the working directory of the invoking shell.

One can delete the current directory from inside it—and then be «in» a nonexistent directory. rmdir ../tmp , from an empty directory called tmp , will do that. The technique in this answer doesn’t delete the current directory because the rm command special-cases the specific pathnames . and .. , refusing to operate on them. Thus rm: refusing to remove ‘.’ or ‘..’ directory: skipping ‘.’ (from GNU rm, which provides /bin/rm in Ubuntu) is quite literally what is happening. rmdir . behaves similarly, though it shows a less illuminating Invalid argument error. @DavidFoerster

  1. Easiest thing for me — a windows expert but an ubuntu newbie
  2. Click the Files icon on the launcher
  3. Navigate to the directory where the files and folders are located that you want to delete
  4. Right Click in a blank area of the window next to the files and click «Open in Terminal» — leave the Files window open
  5. A terminal window will open and will be «set» to the folder you located
  6. You can type «dir» (disregard quotes when i say type) and press enter for the terminal to show a list of files and folders — just to prove you are «in» the right folder
  7. type «rm -rf *» and press enter
  8. depending on size of folders/files to delete system will pause
  9. When terminal prompt returns, the Files window you had opened will now say «Folder is Empty»
  10. I had success with this method and it gave me comfort to see the files/folder both in the Files window and as a result of the Dir command in the terminal window
  11. I was also comforted that the Files window displayed the folder now empty — especially since I had been chasing these files around looking for the trash folder that they were in
  12. Thanks to everyone else who submitted answers — it was very informative
Читайте также:  Linux cnc orange pi

Источник

How to remove files and directories quickly via terminal (bash shell) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.

This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.

From a terminal window: When I use the rm command it can only remove files.
When I use the rmdir command it only removes empty folders. If I have a directory nested with files and folders within folders with files and so on, is there a way to delete all the files and folders without all the strenuous command typing? If it makes a difference, I am using the Mac Bash shell from a terminal, not Microsoft DOS or Linux.

Just in case you wish to restore the files in future , don’t use «rm» for such cases . Use «rm-trash» : github.com/nateshmbhat/rm-trash

4 Answers 4

-r «recursive» -f «force» (suppress confirmation messages)

+1 and glad you added the «Be careful!» part. definitely a «Sawzall» command that can quickly turn a good day into a bad one.. if wielded carelessly.

@itsmatt: You know what they say. give someone a Sawzall, and suddenly every problem looks like hours of fun!

On a Mac? Do this instead: brew install trash then trash -rf some_dir This will move the unwanted directory into your trashbin instead of just vanishing Prestige-style into the ether. (source)

Would remove everything (folders & files) in the current directory.

But be careful! Only execute this command if you are absolutely sure, that you are in the right directory.

Yes, there is. The -r option tells rm to be recursive, and remove the entire file hierarchy rooted at its arguments; in other words, if given a directory, it will remove all of its contents and then perform what is effectively an rmdir .

The other two options you should know are -i and -f . -i stands for interactive; it makes rm prompt you before deleting each and every file. -f stands for force; it goes ahead and deletes everything without asking. -i is safer, but -f is faster; only use it if you’re absolutely sure you’re deleting the right thing. You can specify these with -r or not; it’s an independent setting.

And as usual, you can combine switches: rm -r -i is just rm -ri , and rm -r -f is rm -rf .

Also note that what you’re learning applies to bash on every Unix OS: OS X, Linux, FreeBSD, etc. In fact, rm ‘s syntax is the same in pretty much every shell on every Unix OS. OS X, under the hood, is really a BSD Unix system.

Читайте также:  Linux no servers could be reached

Источник

Remove a Directory in Linux – How to Delete Directories and Contents From the Command Line

Ilenia Magoni

Ilenia Magoni

Remove a Directory in Linux – How to Delete Directories and Contents From the Command Line

Linux is a popular open source operating system, and its features are often available in your development environment. If you can learn its basic commands, it’ll make your life as a developer much easier.

In this guide you will learn how to delete directories and files from the Linux command line.

The Linux rm Command

The rm (short for remove) command is pretty useful. Let’s learn its syntax and look at a few examples to see it in action.

rm Command Syntax

The syntax is shown below, with args being any number of arguments (folders or files).

Without options you can use it to delete files. But to delete directories you need to use the options for this command.

The options are as follows:

  • -r , «recursive» – this option allows you to delete folders and recursively remove their content first
  • -i , «interactive» – with this option, it will ask for confirmation each time before you delete something
  • -f , «force» – it ignores non-existent files and overrides any confirmation prompt (essentially, it’s the opposite of -i ). It will not remove files from a directory if the directory is write-protected.
  • -v , «verbose» – it prints what the command is doing on the terminal
  • -d , «directory» – which allows you to delete a directory. It works only if the directory is empty.

Linux rm Command Example

Let’s take a project_folder directory as an example. It has these files and folders inside:

Let’s use this directory to show how the various options work.

You can add the option -v to all commands so that it will write down step by step what’s going on.

So, let’s start with the first option, -r . You just learned that this removes files and folders recursively. You can use it like this rm -r project_folder or also rm -rv project_folder as the verbose option.

image-98

It has deleted the project_folder directory and everything inside it, in the order shown.

Let’s recreate the folder and try again.

What happens if you don’t use the -r option and you try to delete the directory anyway? It will not allow it and will instead show an error:

image-99

To delete directories you can use the -d option, but if you try to use it in this case it will give an error as the folder is not empty.

image-106

The -i option make so that it asks about each action individually.

And you need to press y or n and then Enter after each query.

If you select y for all queries it will delete everything:

image-107

If instead you decide to not delete some files or folders, with n it will keep those files and continue with the rest:

image-109

The last option we haven’t seen so far is -f , which will suppress errors.

For example writing as below you would be trying to delete two non existing files – there is not a rat.png file, and dog.pmg has a typo and it gives two errors. With the -f option, you will not see the errors.

image-108

Conclusion

The Linux command line is pretty useful if you’re a developer. In this article, you have seen one of its possible commands, rm , that you can use to delete directories and files.

Enjoy this new tool in your arsenal!

Источник

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