How to Escape Shell Characters for unrar
Passing filenames with special shell characters—such as brackets,
spaces, dollar signs, and asterisks—to the unrar
command-line utility often leads to syntax errors, unintended globbing,
or failed extractions. This guide explains how to properly handle these
characters using single quotes, backslash escaping, argument delimiters,
and safe scripting practices to ensure commands execute reliably across
Unix-like shells.
Use Strong Quoting (Single Quotes)
The simplest and most reliable way to prevent the shell from
interpreting special characters is to wrap the filename in single quotes
('). Unlike double quotes, single quotes preserve the
literal value of every character within the string, preventing variable
expansion ($), command substitution (` or
$()), and path expansion (*, ?,
[]).
unrar x 'Archive [2023] (Final) $100.rar'If the filename contains a literal single quote, close the quote, insert an escaped quote, and reopen the quote:
unrar x 'Bob'\''s Archive.rar'Manual Backslash Escaping
Alternatively, individual shell-sensitive characters can be escaped
by prefixing them with a backslash (\). This prevents the
shell from treating them as metacharacters.
Characters requiring escaping include spaces, tabs, parentheses, brackets, quotes, ampersands, semicolons, and wildcards:
unrar x Archive\ \[2023\]\ \(Final\)\ \$100.rarHandle Leading Hyphens with the End-of-Options Delimiter
If a filename begins with a hyphen (for example,
-archive.rar), unrar will interpret the
filename as a command-line flag or switch, resulting in an "Unknown
option" error. To resolve this, use the standard double-hyphen delimiter
(--) to signal the end of command-line switches before
supplying the filename:
unrar x -- '-my-archive.rar'Alternatively, specify the relative path explicitly:
unrar x ./-my-archive.rarDisabling unrar Internal Wildcards
unrar has its own internal pattern-matching engine. Even
if the shell ignores square brackets, unrar might treat
[name] as a wildcard character set. To force
unrar to treat brackets as literal characters in file
extraction targets, escape the brackets with a backslash inside single
quotes so that the backslash reaches the unrar binary
itself:
unrar x 'archive\[1\].rar'Safe Invocation in Scripts
When writing scripts, avoid constructing commands by concatenating strings inside a shell. Instead, pass filenames as discrete arguments via arrays or execution lists:
- Bash Array:
file="Archive [2023].rar" unrar x -- "$file" - Python:
import subprocess filename = "Archive [2023].rar" subprocess.run(["unrar", "x", "--", filename])
Bypassing intermediate shell interpretation entirely eliminates the need for escaping and prevents shell injection vulnerabilities.