How to Delete Files and Directories on Ubuntu Server

When managing an Ubuntu Server, you may need to delete files and directories – for instance, to free up disk space or remove outdated or erroneous data.

Warning

This task should be approached with caution to avoid unintended data loss.

  • Backup: Before proceeding with deletion, ensure that all important files and directories are backed up.
  • Accuracy: Double-check all commands to ensure accuracy before executing them.

Pre-Requisites

  • An Ubuntu Server
  • Access to the terminal

Deleting Files

Single File Deletion

  1. Open the terminal on your Ubuntu server.
  2. Navigate to the directory containing the file you wish to delete.
  3. Run the following command:
    rm filename.extension

Multiple File Deletion

  1. Navigate to the desired directory.
  2. Run the following command:
    rm file1.extension file2.extension

Deleting Directories

Empty Directory Deletion

  1. Navigate to the directory above the one you wish to delete.
  2. Run the following command:
    rmdir directoryname

Directory and All Contents Deletion

  1. Navigate to the directory above the one you wish to delete.
  2. Run the following command:
    rm -r directoryname

Output

When a file or directory is deleted successfully, there will not be any output.

However, if there is an error, you will receive an error message.

For example, attempting to remove a non-empty directory with rmdir will result in the following error message:

rmdir: failed to remove 'directoryname': Directory not empty

Be mindful that deletion actions are irreversible, and once executed, the data is permanently erased from the server. Hence, adhere to the warnings mentioned at the start of this article to prevent any unintended data loss.