Batch RAR Conversion: A Safe CLI and Automation Workflow

November 08, 2026 · RAR.now Editorial · RAR Essentials

Design a repeatable RAR batch process with canaries, logs, validation and rollback.

Phase 1: Source Validation

Before any conversion attempt, validate the source archive with three independent checks:

  1. Hex signature verification—RAR 5.x archives begin with 52 61 72 21 1A 07 01 00 (ASCII Rar!\x1a\x07\x01\x00). RAR 4.x begins with 52 61 72 21 1A 07 00. Use xxd -l 8 or od -A x -t x1z -N 8 to confirm the format version before selecting conversion flags. Per RARLAB technote §File identification, the seventh byte distinguishes major versions.

  2. Full integrity test—unrar t "$archive" decompresses every block through the CRC-32 check chain. Exit code 0 means every file header, data block, and recovery record passed. Any non-zero exit code aborts the pipeline for that archive. Capture stderr separately; unrar t writes diagnostic lines like CRC failed or Unexpected end of archive only to stderr.

  3. Source checksum—compute SHA-256 of the compressed archive file itself and store it alongside the log entry. This is not a content hash; it fingerprints the source bytes so you can later prove the original was not altered after conversion.

source_sig=$(xxd -l 8 -p "$src")
source_sha=$(sha256sum "$src" | cut -d' ' -f1)
unrar t "$src" >/dev/null 2>>"$errlog"
if [ $? -ne 0 ]; then
  printf '%s\tFAIL_SOURCE\t%s\t-\tCRC\t%s\t-\t%s\n' \
    "$(date -Iseconds)" "$src" "$source_sha" "$(tail -1 "$errlog")" >> "$logfile"
  continue
fi

Phase 2: Controlled Recompression

Invoke rar a with every flag explicit. RAR defaults vary by compile-time options and rar.ini contents; relying on them produces archives with unknown characteristics.

rar a -ma5 -md64m -m3 -rr10 -s -ep1 -idq -t \
  "${dst}/${base}.rar" "${workdir}/"*
Flag Effect Hard Limit
-ma5 RAR 5.0 archive format Required for files >4 GB; incompatible with RAR 4.x readers
-md64m 64 MB dictionary Maximum 1 GB (-md1g) in RAR 5; larger dictionaries increase memory pressure linearly during extraction
-m3 Compression level 3 (normal) Range 0–5; -m5 can triple CPU time for 3–7% size reduction on already-compressed payloads
-rr10 10% recovery record Recovery record size is a percentage of total archive size; 10% protects against ~5% random corruption
-s Solid archive Solid archives compress across file boundaries; extraction of a single file requires decompressing all preceding files
-ep1 Strip base path Without this, stored paths include the full temporary directory path
-idq Quiet mode Suppresses per-file progress; errors still print to stderr
-t Test after archiving Runs an internal integrity pass equivalent to unrar t immediately after creation

Dictionary Size Selection

Dictionary size is the dominant factor in both compression ratio and memory consumption. Extraction requires approximately 6× dictionary size in RAM per the RAR 5 algorithm described in RARLAB technote §Compression. Choose based on total uncompressed size of the archive contents:

  • <100 MB total—-md16m (16 MB dictionary, ~96 MB extraction RAM)
  • 100 MB–1 GB—-md64m (64 MB dictionary, ~384 MB extraction RAM)
  • 1 GB–10 GB—-md256m (256 MB dictionary, ~1.5 GB extraction RAM)
  • >10 GB—-md1g (1 GB dictionary, ~6 GB extraction RAM)

Setting dictionary larger than uncompressed data wastes RAM with no compression benefit.

Phase 3: Target Verification and Atomic Deletion

Verification must confirm both archive integrity and content fidelity. Archive integrity alone is insufficient—a successful unrar t proves the bitstream is well-formed but does not prove the extracted bytes match the source.

Content Comparison Without Full Extraction

Extracting both archives to disk doubles space requirements and risks filling the filesystem. For archives where you control the source extraction, use streaming comparison:

# Compare extracted content byte-for-byte without temporary files
diff <(unar p "$src" | sha256sum) <(unar p "$target" | sha256sum)

unrar p writes extracted data to stdout in archive order. Piping through sha256sum produces a single hash of the concatenated stream. Identical hashes mean identical byte streams in identical order. This method fails if the source and target archives store files in different order—which occurs if you re-created the archive from extracted files rather than repacking the original stream.

Deletion Guard

Only delete the source after both checks pass. Write the log entry before deletion so a crash during rm leaves an audit trail:

if unrar t "$target" >/dev/null 2>&1 && \
   [ "$(unar p "$src" | sha256sum | cut -d' ' -f1)" = \
     "$(unar p "$target" | sha256sum | cut -d' ' -f1)" ]; then
  target_sha=$(sha256sum "$target" | cut -d' ' -f1)
  printf '%s\tOK\t%s\t%s\t%s\t%s\n' \
    "$(date -Iseconds)" "$src" "$target" "$source_sha" "$target_sha" >> "$logfile"
  rm "$src"
else
  printf '%s\tROLLBACK\t%s\t%s\tHASH_MISMATCH\t%s\t-\n' \
    "$(date -Iseconds)" "$src" "$target" "$source_sha" >> "$logfile"
  rm -f "$target"
fi

Failure Logging and Rollback

Log Schema

Write a single tab-separated file with fixed columns. No optional fields, no JSON—the log must be parseable with cut in recovery scenarios where no JSON parser is available:

TIMESTAMP  STATUS  SOURCE  TARGET  SOURCE_SHA  TARGET_SHA  NOTE
  • STATUS is one of OK, FAIL_SOURCE, CONVERSION_FAIL, VERIFICATION_FAIL, HASH_MISMATCH, ROLLBACK.
  • SOURCE_SHA is the SHA-256 of the compressed source archive, computed in Phase 1.
  • TARGET_SHA is the SHA-256 of the compressed target archive; - if no target was created.
  • NOTE contains the first line of stderr from the failing command, truncated to 200 characters.

Rollback Rules

Failure Point Action Source Disposition
Source fails unrar t Log FAIL_SOURCE, skip archive Untouched
rar a returns non-zero Log CONVERSION_FAIL, delete partial target Untouched
Target fails unrar t Log VERIFICATION_FAIL, delete target Untouched
Content hash mismatch Log HASH_MISMATCH, delete target Preserved, flagged for manual inspection
All checks pass Log OK, delete source Deleted

Content hash mismatch is the highest-severity non-failure: the archive is structurally valid but the bytes differ. This indicates either metadata transformation (timestamps, permissions, file ordering) or silent data corruption in the compression path. Do not delete the source in this case.

Canary Archives and Dry Runs

Canary Construction

Before processing a production batch, construct a canary archive with known content and run the full pipeline against it. The canary must exercise every code path: multiple files, a binary payload, and a recovery record.

echo "canary-$(date +%s)" > canary_meta.txt
dd if=/dev/urandom bs=1M count=10 of=canary_data.bin 2>/dev/null
rar a -ma5 -m3 -rr10 canary.rar canary_meta.txt canary_data.bin
sha256sum canary.rar > canary.rar.sha256

Run the conversion pipeline against canary.rar. Confirm the target passes unrar t, the content hash matches, and the log contains an OK line. Delete the canary target and re-run. If the canary fails, investigate before touching production data. Common causes: wrong rar version (check with rar | head -1), insufficient disk space, or RAR_UMASK restricting write permissions.

Dry Run Implementation

A --dry-run flag must print every action without executing deletions or writing to the production log. It must still run unrar t on sources—a dry run that skips validation is useless:

if [ "$DRY_RUN" = true ]; then
  echo "DRY: unrar t $src (exit: $?)"
  echo "DRY: rar a -ma5 ... ${dst}/${base}.rar"
  echo "DRY: Would delete $src after verification"
  continue
fi

Multi-Volume and Encrypted Archives

Volume Sets

Multi-volume RAR archives use the naming convention .part1.rar, .part2.rar (RAR 5) or .r00, .r01 (RAR 4). Process only the first volume. unrar t on the first volume tests the entire set; if any volume is missing or corrupt, it fails with Cannot find volume.

Before conversion, verify all volumes are present:

# RAR 5 volume detection
first_vol="$src"
vol_dir=$(dirname "$src")
vol_base=$(basename "$src" .part1.rar)
expected_vols=$(ls "$vol_dir/${vol_base}.part"*.rar 2>/dev/null | wc -l)
unrar t "$first_vol" >/dev/null 2>&1
if [ $? -ne 0 ]; then
  echo "Volume set incomplete or corrupt: $first_vol"
  continue
fi

The target should be a single-volume RAR unless the uncompressed size exceeds 2^63 bytes (RAR 5 maximum file size per RARLAB technote §File size). Multi-volume targets complicate verification and rollback; avoid them unless required by media constraints.

Encrypted Archives

RAR 5 uses AES-256 in CTR mode for file data and PBKDF2-HMAC-SHA256 for key derivation. If the source archive is encrypted, the conversion must preserve encryption with identical parameters.

  • File encryption only (-p)—unrar t works without the password because file headers are plaintext. Content comparison via unrar p requires the password.
  • Header encryption (-hp)—unrar t fails without the password because file names and metadata are encrypted. You cannot validate content without the password; automated rollback logic is blind.
# Pass-through encryption with identical password
rar a -ma5 -hp"${RAR_PASSWORD}" -rr10 -s -ep1 -idq \
  "${target}" "${workdir}/"*

Hard limit: If the source uses -hp and you do not have the password, skip the archive. Log it as FAIL_SOURCE with note header_encrypted_no_password. Attempting conversion without the password produces an archive with different encryption (or none), which is a silent data transformation.

Hard Limits and Edge Cases

Condition Limit Detection
File path > 65,535 bytes RAR 5 maximum path component length `unrar vb "$src" awk 'length > 65535'`
Archive > 2^63 bytes uncompressed RAR 5 theoretical maximum `unrar v "$src" grep 'Total size'`
Solid archive with > 100,000 files Extraction memory scales with file count during content comparison `unrar v "$src" grep 'Files:'`
Disk space < 2× source archive size Temporary extraction or solid archive decompression may fail `df "$tmpdir" awk 'NR==2 {print $4}'`
Recovery record < 3% Below 3%, a single sector loss can corrupt the archive `unrar v "$src" grep 'Recovery record'`

For solid archives with more than 10,000 files, streaming content comparison (unrar p | sha256sum) is mandatory—extracting to disk for per-file hashing will exhaust inodes or space on most filesystems.

Reference Implementation Constraints

A production script must enforce these constraints at startup:

  1. rar and unrar must be from RARLAB, not unrar-free or unar. Check with rar | head -1 for the string RAR and version ≥5.0.
  2. $TMPDIR must have free space ≥2× the largest source archive. Abort if not.
  3. Log file must be on a different physical device than source archives to survive a disk failure during conversion.
  4. RAR_UMASK=022 must be set to ensure target archives are readable by group and world; the default umask can produce owner-only files.
# Startup guard
if ! rar 2>&1 | grep -q 'RAR [5-9]'; then
  echo "FATAL: rar 5.x+ required" >&2
  exit 1
fi

largest=$(stat -c%s "$src_dir"/*.rar | sort -n | tail -1)
free_space=$(df --output=avail "$tmp_dir" | tail -1)
if [ "$free_space" -lt $((largest * 2)) ]; then
  echo "FATAL: insufficient space in $tmp_dir" >&2
  exit 1
fi

export RAR_UMASK=022

When Not to Batch Convert

Skip batch conversion when:

  • Archives use -ms (store without compression) and you need to preserve the exact byte layout—recompression with -ms may reorder files.
  • Archives contain NTFS alternate data streams (-ow flag)—RAR 5 stores them but extraction on non-NTFS filesystems silently drops them.
  • Archives use RAR 4.x format and your consumers require RAR 4.x compatibility. RAR 5 is not backward-compatible. Use -ma4 and accept the4 GB per-file limit and absence of AES-256 encryption.
  • The source archive's recovery record has already been used for repair. The repaired archive may have structural differences from the original; convert the repaired version only after manual verification.

For these cases, process each archive individually with manual inspection of unrar v output before and after conversion.