7 releases (4 breaking)
new 0.5.0 | Nov 27, 2023 |
---|---|
0.4.0 | Nov 23, 2023 |
0.3.2 | Oct 26, 2023 |
0.3.0 | Apr 3, 2022 |
0.1.0 | Feb 5, 2020 |
#227 in Encoding
1,710 downloads per month
Used in 4 crates
(3 directly)
28KB
405 lines
shell-quote
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.
Examples
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]'");
Dependencies
~690KB