You can use the following commands to empty directory in Linux and Unix like systems.
How To Empty Directory In Linux and Unix
- rm command – Delete one or more files or directories.
- find command – Find and delete all files from a specific directory.
Linux Empty Directory Using the rm Command
First, consider the following directory structure displayed using the tree command
/tmp/ | |------foo/ |---file1 |---file2 |---file3
Delete All Files Using the Find Command
Consider the following directory structure:
/tmp/ | |------bar/ | |---file1.txt |---file2.txt | |---subdir1/ | |---file1.doc | |---file2.doc | |---subdir2/ |---image1.jpg |---image2.png
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
$ 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:
- -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.
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.
🐧 9 comments so far... add one ↓
|Category||List of Unix and Linux commands|
|Disk space analyzers||df • ncdu • pydf|
|File Management||cat • cp • mkdir • tree|
|Firewall||Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04|
|Network Utilities||NetHogs • dig • host • ip • nmap|
|OpenVPN||CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04|
|Package Manager||apk • apt|
|Processes Management||bg • chroot • cron • disown • fg • jobs • killall • kill • pidof • pstree • pwdx • time|
|Searching||grep • whereis • which|
|User Information||groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w|
|WireGuard VPN||Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04|