#shell #bash #escaping #quote #sh

shell-quote

A Rust library for shell-quoting strings, e.g. for interpolating into a Bash script.

7 releases (4 breaking)

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

#199 in Encoding

Download history 655/week @ 2023-12-04 125/week @ 2023-12-11 326/week @ 2023-12-18 122/week @ 2024-01-01 453/week @ 2024-01-08 176/week @ 2024-01-15 115/week @ 2024-01-22 234/week @ 2024-01-29 348/week @ 2024-02-05 379/week @ 2024-02-12 1401/week @ 2024-02-19 2438/week @ 2024-02-26 1913/week @ 2024-03-04 2535/week @ 2024-03-11 2598/week @ 2024-03-18

9,502 downloads per month
Used in 5 crates

Apache-2.0

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

~685KB