How to Delete Archive After Unrar Extraction
The unrar command-line utility does not include a native
flag to automatically delete source archives upon extraction. However,
you can safely delete the archive file immediately after a successful
extraction by using shell conditional operators. This guide explains how
to chain the extraction and cleanup commands across Linux, macOS, and
Windows environments, ensuring archives are removed only when the
extraction finishes without errors.
The Standard Command: Conditional Execution
Because unrar returns an exit code of 0
when an extraction completes successfully, you can pair it with your
shell's logical AND operator (&&). If
the extraction encounters errors, the cleanup command will not execute,
protecting your data from accidental loss.
Linux and macOS (Bash / Zsh)
For a single archive:
unrar x archive.rar && rm archive.rarFor multi-part archives (e.g., archive.part1.rar,
archive.part2.rar):
unrar x archive.part1.rar && rm archive.part*.rarNote: Use x instead of e to preserve
the original directory structure within the archive.
Windows Command Prompt (CMD)
For a single archive:
unrar x archive.rar && del archive.rarFor multi-part archives:
unrar x archive.part1.rar && del archive.part*.rarWindows PowerShell
In PowerShell, execute the extraction and check the process exit code:
unrar x archive.rar; if ($LASTEXITCODE -eq 0) { Remove-Item archive.rar }For multi-part archives:
unrar x archive.part1.rar; if ($LASTEXITCODE -eq 0) { Remove-Item archive.part*.rar }Batch Processing Multiple Archives
To process and clean up multiple RAR files in a directory on Linux or
macOS, use a for loop:
for f in *.rar; do
unrar x "$f" && rm "$f"
doneFor Windows Command Prompt:
for %f in (*.rar) do unrar x "%f" && del "%f"How Exit Codes Protect Your Data
The && operator checks the exit code of
unrar before proceeding to deletion. The primary exit codes
for unrar include:
- 0: Successful operation (archive is deleted).
- 1: Non-fatal error occurred (archive is preserved).
- 2: A fatal error occurred (archive is preserved).
- 3: CRC error / corrupted archive (archive is preserved).
- 4: Attempt to modify a locked archive (archive is preserved).
- 5: Write error to destination disk (archive is preserved).
Because deletion is gated behind exit code 0, incomplete
or corrupted extractions will never result in the loss of your original
archive files.