- Delete / Remove a Directory Linux Command
- Commands to remove a directory in Linux
- rmdir command syntax to delete directory in Linux
- Delete directory Linux Command
- How to see a diagnostic message for every directory processed
- Removing directories with rmdir and wildcards
- Linux remove entire directory including all files and sub-directories command
- Are you getting permission denied error message while removing directories?
- Use find command to delete unwanted directories
- How to find and remove all empty directories
- Conclusion
- Linux Delete All Files In Directory Using Command Line
- Linux Delete All Files In Directory
- How to remove all the files in a directory?
- Understanding rm command option that deleted all files in a directory
- Deleting hidden vs non-hidden files
- Bash remove all files from a directory including hidden files using the dotglob option
- Linux Remove All Files In Directory
- Conclusion
- Linux / Unix: Find And Remove Files With One Command On Fly
- Find And Remove Files With One Command On Fly
- Examples of find command
- Conclusion
- How To Delete File In Linux?
- rm Command Syntax
- rm Command Help
- Delete Single File with rm Command
- Delete Multiple Files with rm Command
- Delete Files According To Their Extensions/Types with rm Command
- Delete Files Recursively
- Delete File with Prompt Before Every Removal
- Print Verbose Output About Delete Operation
- Delete empty Directories or Folders with rmdir Command
- Read File Names From Text File For Delete or Removal
- Delete File Names Starts with Dash —
- Delete Files By Reading Their Names From A File/List
- Delete Files By Finding them with find Command
Delete / Remove a Directory Linux Command
Commands to remove a directory in Linux
There are two command to delete a folder in Linux:
- rmdir command – Deletes the specified empty directories and folders in Linux.
- rm command – Delete the file including sub-directories. You can delete non-empty directories with rm command in Linux.
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 Delete All Files In Directory Using Command Line
Linux Delete All Files In Directory
The procedure to remove all files from a directory:
- Open the terminal application
- To delete everything in a directory run: rm /path/to/dir/*
- 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
Источник
Linux / Unix: Find And Remove Files With One Command On Fly
However, the rm command does not support search criteria. For example, find all “*.bak” files and delete them. For such necessities, you need to use the find command to search for files in a directory and remove them on the fly. You can combine find and rm command together. This page explains how to find and remove files with one command on fly.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | find command |
Est. reading time | 4 minutes |
Find And Remove Files With One Command On Fly
The basic find command syntax is as follows:
find dir-name criteria action
Where,
- dir-name : – Defines the working directory such as look into /tmp/
- criteria : Use to select files such as “*.sh”
- action : The find action (what-to-do on file) such as delete the file.
You want to remove multiple files such as ‘*.jpg’ or ‘*.sh’ with one command find, try:
find . -name «FILE-TO-FIND» -exec rm -rf <> \;
OR
find /dir/to/search/ -type f -name «FILE-TO-FIND-Regex» -exec rm -f <> \;
The only difference between above two syntax is that the first command remove directories as well where second command only removes files. Where, 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 ➔
- -name «FILE-TO-FIND» : File pattern.
- -exec rm -rf <> \; : Delete all files matched by file pattern.
- -type f : Only match files and do not include directory names.
- -type d : Only match dirs and do not include files names.
Modern version of find command has -delete option too. Instead of using the -exec rm -rf <> \; , use the -delete to delete all matched files. We can also explicitly pass the -depth option to the find to process each directory’s contents before the directory itself. It is also possible to use the -maxdepth option to control descend at most levels of directories below the starting-points. For example, -maxdepth 0 means only apply the tests and actions to the starting-points themselves. Similary, we can pass the -mindepth to the find. It means do not apply any tests or actions at levels less than levels (a non-negative integer). For exampe, -mindepth 1 means process all files except the starting-points. So here is a simplied syntax:
find /dir/to/search/ -type f -name «FILES-TO-FIND» -delete
find /dir/to/search/ -type f -name «FILES-TO-FIND» -depth -delete
find /dir/to/search/ -maxdepth 2 -type f -name «FILES-TO-FIND» -depth -delete
Examples of find command
Find all files having .bak (*.bak) extension in the current directory and remove them:
find . -type f -name «*.bak» -exec rm -f <> \;
OR
find . -type f -name «*.bak» -delete
Find all core files in the / (root) directory and remove them (be careful with this command):
# find / -name core -exec rm -f <> \;
### OR ###
# find / -name core -delete
Find all *.bak files in the current directory and removes them with confirmation from user:
$ find . -type f -name «*.bak» -exec rm -i <> \;
Sample outputs:
The -delete always works better because it doesn’t have to spawn an external process such as rm for every matched file. However, the -delete option may not available on all find versions. Hence, we can use the xargs command as follows too:
find . -type f -name «*.err» -print0 | xargs -I <> -0 rm -v «<>»
Where the find command option is as follows:
- -print0 – Force find command to print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs.
And the xargs command options are as follows:
- -I <> : Replace occurrences of <> in the initial-arguments with names read from standard input. We pass <> as arg to the rm command.
- -0 : Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end of file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode.
- rm -v «<>« : Run rm command on matched files.
Conclusion
Read the following man pages using the man command:
man find
man xargs
man rm
For detailed information on find command please see finding/locating files with find command part # 1, Part # 2.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
How To Delete File In Linux?
Deleting files in Linux can be sometimes tricky. We have a tool named rm which is the shortcut for the word remove. In this tutorial, we will look at how to remove or delete a file in Linux with different examples and ways.
rm Command Syntax
rm command syntax is the same as the most the Linux command. We can provide options before specifying the file and directories we cant to operate or delete.
- OPTINS states the behavior of the rm command as we will see below in detail.
- FILENAME is the file or directory name we want to delete or operate.
rm Command Help
rm command help information can be printed to the console with the —help command which is like below. Help information will provide some popular options and usages.
Delete Single File with rm Command
We will start with simple steps just deleting a single file. We will just specify the file name we want to delete. In order to remove the file successfully, we should have privileges to modify a file. For example, if we try to remove the file owned by root with a regular user we will get an error and would not delete the file. In this example, we will delete the file named foo.txt
Delete Multiple Files with rm Command
We have the ability to delete multiple files in a single rm command. We will just put file names we want to delete by separating them with space. In this example, we will delete file names foo.txt and bar.txt but we can add more if we need it.
Delete Files According To Their Extensions/Types with rm Command
Linux bahs provides the glob or asterisk in order to specify the files with a specific name or extension. We can use glob * in order to specify a specific extension like *.txt , *.pdf , *.tmp etc. We can use this extension or name specification in order to delete specific files. In this example, we will delete all *.deb extensions.
We can also specify names like deleting all files which name starts with pof like below.
Delete Files Recursively
rm command provides the ability to delete or remove files recursively. Recursive removal will check subdirectories for files to remove with the directories. We will remove the directory name ndiff with all sub-directories and files in this example. We will use -R option for the recursive operation.
Delete File with Prompt Before Every Removal
While removing files and directories we may need approval for each file to delete. In this case, we can use -i option which will prompt to accept or deny deletion of the given file.
Print Verbose Output About Delete Operation
While deleting files and directories we may want to see details of the removal operation. rm command provides a verbose option which will list information about each deletion of file or directory. We will use -v option for this.
Delete empty Directories or Folders with rmdir Command
In some cases, we need to delete empty folders. rm without options will not work in this case as we can see this in the following screenshot. We case use rmdir command to remove an empty directory or folder.
Read File Names From Text File For Delete or Removal
Another interesting use case for rm command is providing file or directory names from a list like a text file. We will use xargs command to-read the list and redirect to the rm command.
Delete File Names Starts with Dash —
Another interesting case is dash or — problem where file or directory names starting with dash . As we know Linux commands options are specified with dash . So how can rm recognize file name from option? We will use — or double dash were to specify the file or directory name start. For example we have a file named -file.txt and we want to remove. We will use the following command. As we can see the file name is specified after double dash. Options are specified before the double dash.
Delete Files By Reading Their Names From A File/List
In some cases, we may need to read a list that contains the file names we want to delete. This is generally a simple text file where each file name with their path is specified line by line. We can use xargs command to redirect the list contents to the rm command which will delete them one by one. In this example, we will read the list file names file-list.txt .
Delete Files By Finding them with find Command
find is a very useful command which is used to find files and folders. find command also provides some options like running commands on the search results. We can also remove or delete files found by the find command. In this example, we will delete files that are older than 3 days.
Источник