Crate shell_quote

source ·
Expand description


This escapes strings in a way that they can be inserted into shell scripts without the risk that they’re interpreted as, say, multiple arguments (like with Bash’s word splitting), paths (Bash’s pathname expansion), shell metacharacters, function calls, or other syntax. This is frequently not as simple as wrapping a string in quotes.

Inspired by the Haskell shell-escape package, which is the most comprehensive implementation of shell escaping I’ve yet seen.

For now this package implements escaping for /bin/sh-like shells and GNU Bash. Please read the documentation for each module to learn about some limitations and caveats.


When quoting using raw bytes it can be convenient to call Bash’s and Sh’s associated functions directly:

use shell_quote::{Bash, Sh};
assert_eq!(Bash::quote("foobar"), b"foobar");
assert_eq!(Sh::quote("foobar"), b"foobar");
assert_eq!(Bash::quote("foo bar"), b"$'foo bar'");
assert_eq!(Sh::quote("foo bar"), b"'foo bar'");

It’s also possible to use the extension trait QuoteRefExt which provides a [quoted] function:

use shell_quote::{Bash, Sh, QuoteRefExt};
let quoted: Vec<u8> = "foo bar".quoted(Bash);
assert_eq!(quoted, b"$'foo bar'");
let quoted: Vec<u8> = "foo bar".quoted(Sh);
assert_eq!(quoted, b"'foo bar'");

Or the extension trait QuoteExt for pushing quoted strings into a buffer:

use shell_quote::{Bash, QuoteExt};
let mut script: String = "echo ".into();
script.push_quoted(Bash, "foo bar");
script.push_str(" > ");
script.push_quoted(Bash, "/path/(to)/[output]");
assert_eq!(script, "echo $'foo bar' > $'/path/(to)/[output]'");


  • Quote byte strings for use with Bash, the GNU Bourne-Again Shell.
  • A string of bytes that can be quoted/escaped.
  • Quote byte strings for use with /bin/sh.