Tool · POSIX shells
shell quote
Paste any string. See it quoted four ways for bash, sh, dash, zsh: single-quoted, double-quoted, ANSI-C, and printf %q. The forms differ in what they preserve and what they let the shell still interpret.
Quoted forms
Each form is safe to drop into a script. Pick by what you need preserved.
Most defensive. Every byte is literal except the closing quote, which is rewritten as '\''. Works in sh, bash, dash, ksh, zsh.
Escapes $ ` \ " only. Other characters pass through. Use when you want $variable or $(cmd) to expand at runtime.
For control characters and binary bytes. Newlines become \n, tabs \t, NULs \0. Supported in bash, zsh, ksh93. Not POSIX-portable; dash rejects it.
Round-trip safe inside bash: feed this back into bash and you recover the original bytes. Not POSIX-portable. Bash's exact output here varies by version; this implementation picks a safe form rather than mirroring a specific bash release.
Which form, when
| Form | Preserves | Lets the shell interpret | Portable |
|---|---|---|---|
'…' |
Every byte literally | Nothing | POSIX |
"…" |
Most bytes literally | $var, $(cmd), `cmd`, escapes for $ ` \ " |
POSIX |
$'…' |
Bytes via escape codes (\n, \xNN) |
Only the backslash escape codes | bash, zsh, ksh93 only |
printf %q |
Smallest re-parsable form | Nothing (the output is literal-safe) | bash, zsh only |
The single-quote trick
You cannot put a single quote inside single quotes. The POSIX idiom is to close the quote, write the literal quote backslash-escaped, then reopen:
it's becomes 'it'\''s'. Four pieces concatenated by adjacency: 'it' then \' then 's'. Works in every POSIX shell.
Common gotchas
- Double quotes do not protect
$var. If you want the dollar sign literal, single-quote it or backslash-escape\$. - Single quotes do not protect against shell history. In interactive bash,
!may still expand. Disable withset +Hor escape as\!. - ANSI-C is not POSIX. Scripts with
#!/bin/shon Debian and Ubuntu rundash.$'\n'fails there. Useprintf '%b' '\n'or a literal newline inside single quotes instead. - NUL bytes break shell strings entirely. The shell terminates the string at the first NUL. Use
xxd,od, or process substitution if you need to carry binary. - printf %q output uses ANSI-C. The result is not POSIX-portable, only round-trip safe in bash.
References
By Truffle. Source at github.com/truffle-dev/tool-shell-quote. MIT. Sibling tools at /public/tools/.