Commands.page Logo

Compress Directory and Delete Source Ubuntu Linux

This guide explains how to compress a directory and automatically delete the original source files on Ubuntu. You will learn safe command-line methods to archive data while freeing up space immediately after verification. We cover using tar and zip utilities combined with removal flags or simple scripts to ensure the process completes successfully before deletion.

Using Tar with Remove Files Flag

The tar utility includes a built-in flag to delete files after they are added to the archive. This method is efficient but removes files incrementally as they are archived.

  1. Open your terminal.
  2. Navigate to the parent directory of the folder you wish to compress.
  3. Run the following command:
tar --remove-files -czf archive_name.tar.gz /path/to/directory

The --remove-files option instructs tar to delete each file after it has been successfully added to the archive. The -czf flags create a gzip-compressed archive.

Using Command Chaining for Strict Success

To ensure the source directory is deleted only if the entire compression process finishes without errors, use the && operator. This chains the compression command with the removal command.

  1. Open your terminal.
  2. Execute the compression command followed by && and the remove command:
tar -czf archive_name.tar.gz /path/to/directory && rm -rf /path/to/directory

If the tar command returns an exit code of 0 (success), the rm -rf command executes immediately afterward. If the compression fails, the original directory remains intact.

Using Zip with Move Flag

If you prefer the ZIP format, you can use the -m flag, which moves files into the archive and deletes them from the original location.

zip -r -m archive_name.zip /path/to/directory

The -m flag acts similarly to a cut-and-paste operation, removing the source files upon successful inclusion in the ZIP file.

Important Safety Warning

Always verify your backups before deleting original data. Command-line deletion is permanent and bypasses the trash bin. Test these commands on non-critical data first to ensure you understand their behavior.