Handling Unrar Password Prompts in Scripts

Automating archive extraction often stalls when a script encounters a password-protected RAR file, causing the process to hang indefinitely while waiting for user input. This guide covers how to gracefully manage unrar password prompts in non-interactive environments, including how to immediately reject encrypted archives without hanging, how to pass known credentials securely, and how to capture specific exit codes for robust error handling.

Prevent Interactive Hanging with -p-

By default, unrar prompts for a password via stdin whenever it encounters an encrypted file header or payload. In headless environments such as cron jobs or CI/CD pipelines, this blocks execution permanently.

To explicitly instruct unrar not to prompt for a password, use the -p- flag. If the archive requires a password, the command will immediately fail instead of waiting for input:

unrar x -p- -y archive.rar /destination/path/
  • -p-: Disables all password prompts and denies password input.
  • -y: Automatically answers "Yes" to all other interactive prompts, such as file overwrite confirmations.

Passing Known Passwords via CLI

If you know the password in advance, pass it directly to the -p switch. Ensure there is no space between the -p flag and the password itself:

unrar x -p"MySecretPassword" -y archive.rar /destination/path/

To prevent the password from leaking into process monitoring tools (ps, top) or shell history, store it in an environment variable:

unrar x -p"$ARCHIVE_PASSWORD" -y archive.rar /destination/path/

Parsing Exit Codes Gracefully

Handling errors gracefully requires inspecting the return code of the unrar command. When -p- is used on an encrypted archive, unrar terminates with an error code rather than hanging.

Common unrar exit codes include:

  • 0: Success.
  • 1: Non-fatal warning (e.g., files locked).
  • 2: Fatal error.
  • 3: CRC error or incorrect password.
  • 11: Password required or zero-length password supplied.

Here is an example Bash pattern that attempts extraction without waiting, detects encryption failures, and logs them without breaking the automated pipeline:

#!/usr/bin/env bash

ARCHIVE="data.rar"
DEST="/tmp/extracted"

# Attempt extraction without interactive prompts
unrar x -p- -y -idq "$ARCHIVE" "$DEST"
EXIT_CODE=$?

case $EXIT_CODE in
  0)
    echo "Extraction successful."
    ;;
  3|11)
    echo "Error: Archive is password-protected or password was incorrect." >&2
    # Handle the failure (e.g., move to quarantine, notify an admin)
    exit 1
    ;;
  *)
    echo "Error: Extraction failed with exit code $EXIT_CODE." >&2
    exit "$EXIT_CODE"
    ;;
esac

The -idq flag is added here to suppress standard output and display only error messages, keeping script logs clean. Combining -p-, -y, and targeted exit code handling ensures that automated scripts run predictably without hanging on protected files.