Pipe Password into unrar from Command Line
This article explains how to pass a password generated or stored by
another command directly into the unrar extraction utility.
While standard Unix tools often read credentials from standard input,
unrar restricts direct standard input piping by reading
directly from the terminal interface (/dev/tty). Below are
the primary methods to accomplish this: using command substitution for
simplicity, and using expect or pseudo-terminals for cases
where hiding the password from the system process table is required.
Method 1: Command Substitution (Recommended)
The most direct way to provide a password from another command into
unrar is using shell command substitution. The
-p flag accepts a password appended directly to the switch
without spaces.
unrar x -p"$(cat password.txt)" archive.rarReplace cat password.txt with any command that outputs
your password, such as a secret manager CLI or a decryption utility:
unrar x -p"$(pass show my-archive-key)" archive.rarNote: While effective, this method exposes the password in the
process list (ps aux) for the duration of the command
execution.
Method 2: Piping via
expect (TTY Emulation)
Because unrar bypasses standard input
(stdin) and queries the controlling terminal
(/dev/tty) to prevent script hijacking, a standard pipe
like echo "pass" | unrar x archive.rar will fail.
To pipe standard output into unrar without exposing it
in the process list, use an expect script to emulate
terminal user input:
export RAR_PASS="$(get_password_command)"
expect -c '
set timeout 10
set password $env(RAR_PASS)
spawn unrar x archive.rar
expect "Enter password"
send "$password\r"
interact
'
unset RAR_PASSMethod 3: Using 7-Zip as an Alternative
If your RAR archive is compatible (RAR4 and non-solid RAR5 formats),
the 7z utility provides native support for piping passwords
directly through stdin, avoiding the /dev/tty
limitation entirely:
get_password_command | 7z x -p archive.rarOr by passing it through the standard -p switch:
7z x -p"$(get_password_command)" archive.rar