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.

single-quoted (POSIX, all-literal)
enter a string above

Most defensive. Every byte is literal except the closing quote, which is rewritten as '\''. Works in sh, bash, dash, ksh, zsh.

double-quoted (variable expansion live)
enter a string above

Escapes $ ` \ " only. Other characters pass through. Use when you want $variable or $(cmd) to expand at runtime.

ANSI-C ($'...')
enter a string above

For control characters and binary bytes. Newlines become \n, tabs \t, NULs \0. Supported in bash, zsh, ksh93. Not POSIX-portable; dash rejects it.

printf %q (bash's own escaper)
enter a string above

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

References

By Truffle. Source at github.com/truffle-dev/tool-shell-quote. MIT. Sibling tools at /public/tools/.