Deleting files and directories is a common task that Linux administrators and users need to perform regularly. While Linux offers various commands like rm, rmdir, unlink to remove files/folders, caution must be exercised to not accidentally delete important data.
In this comprehensive guide, we will cover the following methods to safely delete files and directories in Linux:
- Removing Single Files
- Removing Multiple Files
- Removing Directories
- Find and Remove Files/Directories
Removing Single Files
To remove a single file in Linux, the core command is rm. But there are a couple of ways to delete a file.
Using unlink
The unlink command can permanently remove a file by unlinking it from the file system:
$ unlink file.txt
Using rm
The rm command is more commonly used for removing files. To delete a file named file.txt:
$ rm file.txt
By default, rm prompts you for confirmation before removing write-protected files. To always prompt before removing any file, use the -i option:
$ rm -i file.txt
To remove a file without any confirmation prompts, pass the -f option:
$ rm -f file.txt
Some other useful options are -v to verbose what is being removed and -r to remove directories recursively.
Removing Multiple Files
You can remove multiple files by passing all the filenames as arguments to rm:
$ rm file1.txt file2.txt file3.txt
Or make use of wildcards and regular expressions:
$ rm *.tmp $ rm file-[1-5].txt
Removing Directories
To remove an empty directory, use the rmdir command:
$ rmdir mydir
To remove a directory recursively including all its contents, pass the -r option to rm:
$ rm -r mydir
And to forcefully delete a directory without prompts, use the -rf option:
$ rm -rf mydir
Warning: Use rm -rf very carefully as it can cause severe data loss if run on the wrong directory, especially by the root user.
Find and Remove Files/Directories
The find command offers more advanced ways to search for files/directories to delete based on various criteria like name, size, permissions, user ownership etc.
Some examples:
# Delete files by path/name $ find /temp -name "*.tmp" -delete$ find /var/log -mtime +30 -delete
$ find . -type d -empty -delete
The key is find‘s ability to match files/folders based on complex conditions, which then can be easily removed using -delete option.
Summary
- Use rm and rmdir carefully to avoid accidental data loss
- Take backups before deleting large number of files
- Leverage find to match and remove files based on different criteria
- Understand fully the impact before using destructive options like rm -rf
Following these best practices will help you stay safe whileproductively managing files/directories in your Linux system.