Remove directory with all files linux

Linux Delete All Files In Directory Using Command Line

Linux Delete All Files In Directory

The procedure to remove all files from a directory:

  1. Open the terminal application
  2. To delete everything in a directory run: rm /path/to/dir/*
  3. To remove all sub-directories and files: rm -r /path/to/dir/*

Let us see some examples of rm command to delete all files in a directory when using Linux operating systems.

How to remove all the files in a directory?

Suppose you have a directory called /home/vivek/data/. To list files type the ls command:
$ ls

Understanding rm command option that deleted all files in a directory

  • -r : Remove directories and their contents recursively.
  • -f : Force option. In other words, ignore nonexistent files and arguments, never prompt. Dangerous option. Be careful.
  • -v : Verbose option. Show what rm is doing on screen.

Deleting hidden vs non-hidden files

In Linux, any file or directory that starts with a dot character called a dot file. It is to be treated as hidden file. To see hidden files pass the -a to the ls command:
ls
ls -a
ls -la
To remove all files except hidden files in a directory use:
rm /path/to/dir/*
rm -rf /path/to/dir/*
rm *
In this example, delete all files including hidden files, run:
rm -rf /path/to/dir1/<*,.*>
rm -rfv /path/to/dir1/

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Bash remove all files from a directory including hidden files using the dotglob option

If the dotglob option set, bash includes filenames beginning with a ‘.’ in the results of pathname expansion. In other words, turn on this option to delete hidden files:

See GNU/bash man page for the shopt command online here:
man bash
help shopt

Linux Remove All Files In Directory

As I said earlier one can use the unlink command too. The syntax is:
unlink filename
For example, delete file named foo.txt in the current working directory, enter:
unlink foo.txt
It can only delete a single file at a time. You can not pass multiple files or use wildcards such as *. Therefore, I strongly recommend you use the rm command as discussed above.

Conclusion

In this quick tutorial, you learned how to remove or delete all the files in a directory using the rm command. Linux offers a few more options to find and delete files. Please see the following tutorials:

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Delete / Remove a Directory Linux Command

Commands to remove a directory in Linux

There are two command to delete a folder in Linux:

  1. rmdir command – Deletes the specified empty directories and folders in Linux.
  2. rm command – Delete the file including sub-directories. You can delete non-empty directories with rm command in Linux.
Читайте также:  Zabbix настройка активного агента windows

Let us see some examples and usage in details delete the directories.

rmdir command syntax to delete directory in Linux

The rmdir command remove the DIRECTORY(ies), if they are empty. The syntax is:
rmdir directory-name
rmdir [option] directory-name
Open the terminal application and run command to delete given directory. For example, delete a folder named dir1:
rmdir dir1

Delete directory Linux Command

Open a command line terminal (select Applications > Accessories > Terminal), and then type the following command to remove a directory called /tmp/docs:
rmdir /tmp/docs
If a directory is not empty you will get an error message that read as follows:
rmdir letters
Sample outputs:

You can cd to the directory to find out and list all files:
$ cd letters
$ ls
Delete those files or directories. In this next example, remove data, foo and bar if bar were empty, foo only contained bar and data only contained foo directories:
cd /home/nixcraft
rmdir -p data/foo/bar

Where,

  • -p : Each directory argument is treated as a pathname of which all components will be removed, if they are empty, starting with the last most component.

How to see a diagnostic message for every directory processed

Pass the -v option to the rmdir command:
$ rmdir -v dir1
Sample outputs:

Removing directories with rmdir and wildcards

We can use wildcards such as ‘*’ and ‘?’ to match and delete multiple directories. For example:
$ ls -l dir*
We have three dirs named dir1, dir2, and dir3. To delete all directories starting with ‘dir’ in the current, you would use the following command:
rmdir -v dir*

Linux remove entire directory including all files and sub-directories command

To remove all directories and subdirectories use the rm command. For example, remove *.doc files and all sub-directories and files inside letters directory, type the following command:

Warning : All files including subdirectories will be deleted permanently when executed the following commands.

$ rm -rf letters/
Sample session:

Where,

  • -r : Attempt to remove the file hierarchy rooted in each file argument i.e. recursively remove subdirectories and files from the specified directory.
  • -f : Attempt to remove the files without prompting for confirmation, regardless of the file’s permissions

Are you getting permission denied error message while removing directories?

Only owners can delete their directories. However, a sysadmin can delete any directories created by anyone on the system. The syntax is:
sudo rmdir /path/to/dir/
sudo rm -rf dir2
When prompted, you need to provide root user or sudo user password.

Use find command to delete unwanted directories

Say you want to find out all directories named ‘session’ and delete them in the current directory, run:
find . -type d -iname ‘session’ -delete

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

How to find and remove all empty directories

Run:
find . -type d -iname ‘session’ -empty -delete
Where,

  • -type d : Only search for directories and ignore all other files.
  • -iname ‘session’ : Search directory named ‘session’. You can use wildcards here too. For example, -iname ‘dir*’ .
  • -empty : Only match empty directories
  • -delete : Deletes all found empty directories only

To delete all ‘.DS_store’ directories stored in /var/www/html, run:
sudo find /var/www/html/ -type d -name .DS_Store -exec rm <> \;
OR
sudo find /var/www/html/ -type d -name .DS_Store -exec rm <> +
The -exec option to the find command run an external command named rm to delete all files. The “ rm <> +/ ” is a better option as it uses one rm command to delete all .DS_Store directories.

Conclusion

This page showed how to delete a directory when it is empty. Further, it showed, how to remove folders using the rm and rmdir commands. See rm help page page for more info:

  • For more information read man pages: rm(1)

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Linux / UNIX: How To Empty Directory

How To Empty Directory In Linux and Unix

  1. rm command – Delete one or more files or directories.
  2. find command – Find and delete all files from a specific directory.
Читайте также:  Как отформатировать флешку с помощью windows

Linux Empty Directory Using the rm Command

First, consider the following directory structure displayed using the tree command

To delete all files from /tmp/foo/ directory (i.e. empty /tmp/foo/ directory), enter:
$ cd /tmp/foo/
$ rm *
OR
$ rm /tmp/foo/*

Delete All Files Using the Find Command

Consider the following directory structure:

To delete all files from /tmp/bar/ directory (including all files from sub-directories such as /tmp/bar/dir1), enter:
$ cd /tmp/bar/
$ find . -type f -delete
OR
$ find /tmp/bar/ -type f -delete
The above find command will delete all files from /tmp/bar/ directory. It will not delete any sub-directories. To remove both files and directories, try:
find /path/to/target/dir/ -delete
The find commands options are as follows:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

  • -type f : Delete on files only.
  • -type d : Remove folders only.
  • -delete : Delete all files from given directory name.

How to remove a full directory and all files in Linux

To remove a directory that contains other files or sub-directories, use the following rm command command. In the example, I am going to empty directory named “docs” using the rm -rf command as follows:
rm -rf /tmp/docs/*
Get verbose outputs:
rm -rfv /tmp/docs/*

The rm command options are as follows:

  • -r : Delete directories and their contents recursively on Linux or Unix-like systems.
  • -f : Forceful removal. In other words, ignore nonexistent files and delete whatever found.
  • -v : Verbose outputs. For example, explain what is being done on screen.

Conclusion

You learned how to use the rm and find command to delete all files and sub-directories on Linux/macOS/*BSD and Unix-like systems. In other words, this is useful to empty folders on Linux. For more information see rm command help page here.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

How to Remove Files and Directories in Linux?

Geekflare is supported by our audience. We may earn affiliate commissions from buying links on this site.

One of the basic file system administration tasks involves creating, modifying, and deleting different types of files and directories. Knowing some basic tools and concepts for file deletion comes in handy and can save you time.

Linux offers several tools that can help us accomplish file removal tasks. Often we need to remove not just a single, but a bunch of files and directories, based on some criteria. It is helpful to know a few common commands and their combinations to get our task done easily.

  • Use the below commands with caution especially the ones which use regular expressions or some search patterns with the find command. An incorrect expression or pattern may delete essential data/system files or simply non-intended files.
  • Always secure the latest backup of important data and system files.
  • Take caution before running such commands especially when running it with Sudo or as superuser (root).

Not so popular. To remove a single file permanently, we can use unlink command.

Remove single file

There’s a more commonly used command for removing files, i.e., rm command, which supports removing one or more files simultaneously.

rm prompts you to confirm file deletion for files that are write-protected else it proceeds to directly remove the file. To make rm always prompt before deleting a file, use -i flag:

rm command deletes without displaying any messages on the screen. To list what rm command is actually doing, use rm with -v flag.

To remove write-protected files without prompting for confirmation, use -f flag.

Remove multiple files

Multiple files can be removed by specifying multiple filenames to rm as arguments.

rm also supports regular expressions. If you want to delete all files named file-name-* , you can use:

We can also specify multiple files using regular expressions. If we want to delete three files that match file-name-1 , file-name-2 and file-name-3 , we can use something like:

Читайте также:  Почему не работает windows store

Remove directory

An empty directory can be deleted using rm command with -d option.

Options supported for file removal can also be combined with directory removal using -d flag as well. For example:

To delete a directory that is non-empty use -r flag.

If you don’t want any prompts before deleting the directory and its contents, use -rf flag. This WILL delete everything inside the directory including the directory itself without any confirmation. Do use caution while using it especially as root.

Find and remove files

For more complex requirements, we can use the find command with different options. To remove all files matching pattern inside a path given by

If we want to remove anything that matches a pattern including directories inside , we can slightly modify the above command as:

Modern versions of the find command support the delete function internally. Here -delete flag replaces rm command while -depth instructs find command to first process the contents of the directory before the directory itself :

The above example is more efficient when working with a large number of files as it doesn’t spawn a new external process for rm command for each matched file. But not all versions of find command (yet) may support -delete flag. As an alternate, we have the option to use xargs command with find as shown in the next example below:

Or use exec command’s + terminator to chain together everything found by find command like xargs:

By default, the find command uses -print flag which we usually skip writing. With xargs , we need to avoid new-line character between each filename. As such -print0 flag instructs find to print null character after every found filename.

Similarly, we specify -0 flag with xargs so that both commands couple up. rm command here deletes the file passed on to by piped find input. For example, the below command will search and remove all *.tmp files from the current user’s home directory (given by

find command offers several ways to search files and directories including ownership, permission, timestamp, etc. We’ll be covering a few such ways that can help us in specific file removal tasks.

Find and remove files by a user

To delete everything inside a given directory owned by a specific user , use:

In the above example, -mindepth flag with value 1 prevents the directory given by from deletion if it matches the find pattern and criteria. Or to delete everything inside a given directory belonging to a particular group , use:

If you do not want to traverse the sub-directories under the search path, you also have the option to use -maxdepth with appropriate directory depth value.

Here’s an example run:

If you want to specify user-id and group-id instead, you can try something like:

Find and remove empty directories

To delete all empty directories inside a given path , you can use:

Instead, to delete all empty files inside a given path , use:

Find and remove files older than X

Sometimes, you may need to delete files older than x days. find has options to read file’s creation ( ctime ), access ( atime ) and modification ( mtime ) times. We can use mtime option with find to find and delete files modified more than x days ago.

For instance, to delete all files with extension log inside /var/tmp with a modification time of 30 days ago or more, we can use:

Find and remove files by permission

Now, we can also delete files based on some specific permission, like:

Or if we want to use a symbolic form for permission, use:

Summing Up

Linux offers unlink , rm and rmdir commands that are simple and can be easily extended with the use of regular expressions. For more advanced needs, you have the option to use a combination of tools like find and xargs to achieve what you need. Other than the examples in this article, you’ve got the option to use find with any of its available flags to customize your search. Refer man pages for respective commands to learn more about them.

Always run find commands without rm or -delete flag and analyze its output to know which files or directories will be impacted by the execution of an actual command. Having proper backup configuration and policy helps not only in case of accidental deletions but also in cases of hardware failures and cyber-attacks.

Источник

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