Removing a directory in PHP. MKDIR and RMDIR command to create and delete a directory How to delete a directory with a Linux file

To delete a file or directory in Linux from command line, use the rm (remove) command.

Be especially careful when deleting files or directories using the rm command, because once a file is deleted, it cannot be recovered.

In this article, we'll show you how to use the rm command to delete files and directories in, with examples and explanations of the most common rm options.

How to delete files

  • To remove a single file, use the rm command followed by the file name:

    rm filename

    If the file is write protected, you will be prompted to confirm it as shown below. To delete a file, type y and press Enter. Otherwise, if the file is not write-protected, it will be deleted without prompting.

    rm: remove write-protected regular empty file "filename"?

  • To delete multiple files at once, use the rm command followed by the file names separated by a space.

    rm filename1 filename2 filename3

    You can also use the wildcard (*) and regular expressions to match multiple files. For example, to delete all files with a .pdf extension in the current directory, use the following command:

    rm *.pdf

    When you use rm with wildcards(*) and regular extensions, it is recommended to list the files using the ls command so that you can see which files will be removed before running the rm command.

  • Use the -i option to confirm each file before deleting:

    rm -i filename(s)

  • To delete files without prompting, even if the files are write-protected, use the -f (force) option:

    rm -f filename(s)

  • You can also combine rm options. For example, to delete all .txt files in the current directory without prompting in detailed mode, use the following command:

    rm -fv *.txt

How to delete directories (folders)

  • To remove an empty directory, use the -d option.

    rm -d dirname

  • To remove non-empty directories and all files inside them, use the r (recursive) option.

    rm -r dirname

    If the directory or file in the directory is write-protected, you will be prompted to confirm the deletion.

  • To remove non-empty directories and all files without prompting, use r (recursive) and the -f option.

    rm -rf dirname

  • To remove multiple directories at once, use the rm command followed by the directory names separated by a space.

    rm -r dirname1 dirname2 dirname3

    Same as in files, you can also use wildcard (*) and regular expressions to match multiple directories.

Conclusion

By now you should have a good understanding of how to use the rm command in Linux and you should be able to safely delete files and directories using the command line.

The rm and rmdir commands delete files and directories on Linux, macOS and other Unix-like systems operating systems. They are similar to the del and deltree commands in Windows and DOS. These commands are very powerful and have quite a few options.

It's important to note that files and directories deleted using rm and rmdir are not moved to the Recycle Bin. They are immediately removed from your computer. If you accidentally deleted files using these commands, you will only be able to restore them from a backup.

How to delete files using rm

The simplest case is deleting a single file in the current directory. Type the rm command, a space, and then the name of the file you want to delete.

Rm file_1.txt

If the file is not in the current working directory, provide the path to the file location.

Rm ./path/to/the/file/file_1.txt

You can pass more than one filename to rm. This deletes all specified files.

Rm file_2.txt file_3.txt

Wildcards can be used to select groups of files to be deleted. Sign * represents multiple characters, and the character ? represents one character. This command will delete all files png images in the current working directory.

Rm * .png

This command will delete all files with the same character extension. For example, this will delete File.1 and File.2, but not File.12.

Rm *.?

If the file is write-protected, you will be prompted to delete the file. You must answer with y or n and press "Enter".

To reduce the risk of using rm with wildcards, use the option -i(interactive). To do this, you must confirm the deletion of each file.

Rm -i * .dat

Option -f(force) is the opposite of interactive. It does not ask for confirmation even if the files are write-protected.

Rm -f filename

How to remove directories using rm

To remove an empty directory, use the option -d(directory). You can use wildcards (* and ?) in directory names just as you can in file names.

Rm -d directory

Providing more than one directory name removes all specified empty directories.

Rm -d directory1 directory2 /path/to/directory3

To remove non-empty directories, use the option -r(recursive). To be clear, this deletes directories and all files and subdirectories contained within them.

Rm -r directory1 directory2 directory3

If the directory or file is write-protected, you will be prompted to confirm the deletion. To remove non-empty directories and suppress these prompts, use the options together -r(recursive) and -f(forced).

Rm -rf directory

Caution is required here. Command error rm -rf may result in data loss or system malfunction. This is dangerous and caution is the best policy. To get an idea of ​​the directory structure and files that will be deleted by rm -rf, use the tree command.

Use apt-get to install this package on your system if you are using Ubuntu or another Debian-based distribution. On other Linux distributions, use your package management tool Linux distribution.

Sudo apt-get install tree

Running the tree command produces an easy-to-understand diagram of the directory structure and files under the directory from which it is run.

You can also specify the path to the tree command so that it runs the tree from another directory on the file system.

Tree path/to/directory

The rm command also has --one-file-system , --no-preserve-root , --preserve-root options, but these are only recommended for experienced users. If you do something wrong, you may accidentally delete all your system files.

How to remove directories using rmdir

There is another command, rmdir, that you can use to remove directories. The difference between rm and rmdir is that rmdir can only delete empty directories. It will never delete files.

The simplest case is deleting one empty directory. As with rm , you can pass multiple directory names to rmdir or rmdir a directory path.

Remove one directory in the current directory by passing its name to rmdir:

Rmdir directory

Remove multiple directories by passing a list of names to rmdir:

Rmdir directory1 directory2 directory3

Remove a directory not in the current directory by specifying the full path to that directory:

Rmdir /path/to/directory

If you try to delete a folder that is not empty, rmdir will give you an error message. In the following example, rmdir successfully and silently deletes the clients directory but refuses to delete the projects directory because it contains files. The projects directory remains exactly as it was, and the files in it are untouched.

When rmdir issues a "Directory not empty" error, it stops processing the directories passed to it on the command line. If you asked to delete four directories and the first one contained files, rmdir will give you an error message and do nothing else. You can force it to ignore these errors with --ignore-fail-on-non-empty to process other directories.

In the following example, two folders have been transferred to rmdir, these are work/reports and work/quotes. The --ignore-fail-on-non-empty option is included in the command. The work/reports folder contains files, so rmdir cannot delete it. The --ignore-fail-on-non-empty option causes rmdir to ignore the error and move on to the next folder it has to process, which is work/quotes. This is an empty folder and rmdir deletes it.

This command was used.

Rmdir --ignore-fail-on-non-empty work/reports /work/quotes

You can use the option -p(parent) to remove a directory and also remove its parent directories. This trick works because rmdir starts at the target directory and then goes back to the parent. This directory should now be empty so it can be removed by rmdir and the process repeats the step back along the path provided by rmdir.

In the following example, the command passed to rmdir is:

Rmdir -p work/invoices

The invoices and work directories are deleted upon request.

Are you using Bash or any other shell? Linux provides flexible and powerful commands to delete directories and files directly from the terminal command line. Some people prefer to have a workflow that revolves around a terminal. Others may have no choice in the matter. They can run on servers without a GUI installed, or in a remote session on a standalone system such as a Raspberry Pi. These teams are perfect for this group of people.

But whatever type of workflow you prefer, these commands lend themselves very well to being included in shell scripts. If the script is run by a cron job, it can help automate routine housekeeping tasks such as cleaning up unwanted log files. If you're exploring this use case, be aware of the power of these commands, check everything thoroughly, and always keep a recent backup.

Operating systems based on the Linux kernel typically store a large number of empty and non-empty directories. Some of them take up a fairly large amount of storage space and often become unnecessary. In this case, the correct option would be to remove them. There are several ways to perform cleaning, each of them is applicable in a specific situation. Let's look at all the available methods in more detail, and you will choose the most suitable one based on your needs.

In this article we will talk about console utilities and additional tools, which are launched by entering commands. However, do not forget that graphical shells are often implemented in distributions. Accordingly, to delete a directory you just need to go to it via file manager, click right click mouse on the icon and select "Delete". Don't forget to empty your trash afterwards. However, this option will not be applicable to all users, so we recommend that you read the following guides.

Before starting to look at the methods, it is important to note that when entering a command, most often you will independently indicate the name of the folder that you want to delete. When you are not at its location, you must provide the full path. If possible, we recommend finding out the parent directory of the object and going to it through the console. This action is completed in just a few minutes:


If you are unable to determine the location, when deleting you will have to enter the full path yourself, so you will have to know it.

Method 1: Standard Terminal commands

The command shell of any Linux distribution contains a set of basic utilities and tools that allow you to perform a wide variety of actions with system settings and files, including deleting directories. There are several such utilities and each will be most useful in a certain situation.

rmdir command

First of all, I would like to touch on rmdir. It is designed to clean the system only from empty directories. Removes them permanently, and the advantage of this tool is the simplicity of its syntax and the absence of any errors. In the console, just write rmdir folder , where folder— the name of the folder in the current location. The tool is activated by pressing a key Enter.

There's nothing stopping you from specifying the full directory path if you can't navigate to the location you want or don't need to. Then the line takes, for example, the following form: rmdir /home/user/folder/folder1 , where user- username, folder is the parent directory, and folder1— folder to delete. Please note that there must be a slash before home, but at the end of the path there must be no slash.

rm command

The previous tool is one of the components of the rm utility. Initially it is intended to delete files, but if you give it the appropriate argument, it will also erase the folder. This option is already suitable for non-empty directories; in this case, you need to enter rm -R folder (or the full path to the directory) into the console. Note the argument -R- it starts a recursive deletion, that is, it affects the entire contents of the folder and itself. It is necessary to be case sensitive when entering because -r- this is a completely different option.

If you want to display a list of all deleted files and folders when using rm, then you will need to slightly modify the line. Enter in "Terminal" rm -Rfv folder and then activate the command.

Once the deletion is complete, information about all directories and individual objects that were previously located at the specified location will be displayed.

find command

Our website already has material with examples. use find in operating systems developed on the Linux kernel. Of course, only the basic and most useful information is presented there. You can get acquainted with it by clicking on the following link, and now we propose to find out how this tool works when you need to delete directories.

  1. As is known, find serves to search for objects within the system. Thanks to the use of additional options, you can find directories with a specific name and delete them immediately. To do this, enter find in the console. -type d -name "folder" -exec rm -rf () \;, where folder is the name of the directory. Be sure to write double quotes when doing this.
  2. A separate line sometimes displays information that such a file or directory does not exist, but this does not mean that it was not found. Just find worked again after deleting the directory from the system.
  3. find ~/ -empty -type d -delete allows you to delete all empty folders on the system. Some of them are only accessible to the superuser, so before find sudo should be added.
  4. Data about all found objects and the success of the operation will appear on the screen.
  5. You can also specify only a specific directory for the tool to search and clean. Then the line will look, for example, like this: find /home/user/Folder/ -empty -type d -delete .

This completes interaction with standard console utilities in Linux. As you can see, there are a large number of them and each is applicable in certain situations. If you want to get acquainted with other popular teams, read our separate material at the link below.

Team rmdir will help us delete an empty directory, that is, a directory without files and folders. The command syntax is very simple:

Rmdir DIRNAME

If the directory is not empty, you will see the following error message.

$ rmdir test rmdir: failed to remove `test": Directory not empty

2. How to delete nested directories in Linux?

Using the option -p you can delete a directory with a subdirectory nested within it.

$ rmdir -p dir1/dir2/dir3

Team rmdir -p dir1/dir2/dir3 this is the equivalent of the command

$ rmdir dir1/dir2/dir3 dir1/dir2 dir1

3. Deleting the content directory

If you need to delete a directory with contents, you can use the command rm:

$ rm -rf DIRNAME

This command will delete a directory, including all files and subdirectories it contains. Use this command with caution, as recovering deleted files will not be an easy procedure.

4. Interactive removal

To avoid accidental deletion necessary files I recommend considering using the -i option to interactively delete files and folders (especially with root rights).

Recursive and interactive directory deletion.

# rm -ir DIRNAME

Interactive file deletion.

# rm -i FILENAME

5. Useful aliases for the rm and rmdir commands

You can use interactive deletion as the default behavior of the rm command.

Alias ​​for constantly executing rm interactively

# alias rm="rm -i"

When using the command rm the command will actually be executed rm -i. But you need to pay attention to one nuance. Do not use the -i option in the future as you will not get the desired effect. Let's look at an example:

In the following command, using -i will not give you the expected effect..

$ rm -irf DIRNAME

In this case, when using an alias, the above command must be run as follows:

$ rm -rf DIRNAME

All the commands below are equivalent and perform the same functionality.

  • rm-fr
  • rm -rf
  • rm -r -f
  • rm -f -r

If you need an expert assessment of a building, I recommend ordering an inspection of finished buildings by specialists from the Technoplast research and production center

Good day, dear readers. Today I would like to talk about deleting a directory in PHP. It would seem that the operation is not complicated, but there are some nuances. Let's look at ways to do this.

PHP has a function for this rmdir(). It takes as an argument the path to the directory you want to delete. However, the directory must be empty- this is the main condition (except for the fact that the user from whom the web server is running must have write rights for the directory). If files are placed in the directory, we will receive an error when calling the function. Accordingly, we come to the conclusion that the directory before using the function rmdir() must be cleaned first.

Online they advise writing a function that will pass as an argument the path to the directory that we need to delete. In the body of the function, it is necessary to organize a listing of the contents of the directory, within the framework of which a check is made to determine whether the file is a directory. If the file is a directory, then this condition the function calls itself. This is necessary to clean out nested directories, and it will work at all nesting levels. Otherwise, the function is applied to the file unlink()- it is designed to delete a file. Outside of this check, in the last step we delete the directory.

Example implementation:

Function recursiveRemoveDir($dir) ( $includes = glob($dir."/*"); foreach ($includes as $include) ( if(is_dir($include)) ( recursiveRemoveDir($include); ) else ( unlink( $include); ) ) rmdir($dir); ) //Remove the tmp directory from the current directory recursiveRemoveDir("tmp");
What problems does this code have?

In simple cases, the directory with all attachments will be deleted. But suppose that in our directory there is a hidden file that begins with a dot, for example, .htaccess. Function glob() is a UNIX glob substitution that does not include hidden files (DOTFILES) by default. For example, if we go to the nix terminal and use bash, we will encounter the same problem (we are talking about hidden files within globs). There is a command in bash to solve this issue: shopt -s dotglob- it allows glob substitution hidden files. In PHP, this can be solved by adding an additional parameter GLOB_BRACE For glob() and expanding the pattern from the first parameter of the function.

$includes = glob("tmp/(,.)*", GLOB_BRACE);
And here there is also a problem - we will encounter an infinite loop, since the array will include values. and.. - which is the current and parent directory at the system level. We will end up with an infinite loop (and not deleting all parent directories) because. as part of the default sorting, the generated array will come first.. - that is, every time we will access the same directory. To solve the problem, we will form an array from these system directories and, in a loop, remove their indices from the main array. There is also the problem of symbolic links. Let's say that the directory being deleted contains a link to another directory, the contents of which we are absolutely not interested in deleting. To solve the problem, before creating recursion, it is necessary to check that the entity is not a reference.

As a result, the function takes the following form:

Function recursiveRemoveDir($dir) ( $includes = glob($dir."/(,.)*", GLOB_BRACE); $systemDots = preg_grep("/\.+$/", $includes); foreach ($systemDots as $index => $dot) ( unset($includes[$index]); ) foreach ($includes as $include) ( if(is_dir($include) && !is_link($include)) ( recursiveRemoveDir($include); ) else ( unlink($include); ) ) rmdir($dir) //Remove the tmp directory from the current directory recursiveRemoveDir("tmp");
The code is working, but in fact it could have been made simpler. In PHP there is a class FilesystemIterator, which by default already has the settings we need. The path to the directory whose listing we need is passed to the constructor. We just need to create an object.

Function recursiveRemoveDir($dir) ( $includes = new FilesystemIterator($dir); foreach ($includes as $include) ( if(is_dir($include) && !is_link($include)) ( recursiveRemoveDir($include); ) else ( unlink($include); ) ) rmdir($dir) //Remove the tmp directory from the current directory recursiveRemoveDir("tmp");
In conclusion, I would like to note one more quick way. The correctness of its use is very doubtful - send the command for execution to SHELL.

System("rm -rf tmp");
I would like to draw your attention to the high memory consumption and to the fact that administrators often prohibit the use of such functions on the server for security reasons.

Tags: php, rmdir, glob, recursion

Share