Function quotemeta::quotemeta

source ·
pub fn quotemeta<P: AsRef<OsStr> + ?Sized>(path: &P) -> Cow<'_, str>
Expand description

Shell-quotes the given OS string into a string.

This takes any &AsRef<OsStr>, so accepts &str/&String, &Path/&PathBuf, OsStr/&OsString, and so on. Note that it’s a reference to an AsRef (for tedious lifetime-related reasons) and so a plain String etc doesn’t work.

Although this is an implementation detail which may change, strings which do not need to be escaped are returned as-is, those with high-bit-set octets will be ANSI-C quoted, and otherwise they will be single-quoted.

use quotemeta::quotemeta;
use std::path::Path;

// "Boring" Unix paths do not need to be quoted.
assert_eq!(quotemeta("/bin/cat"), "/bin/cat");
// Spaces etc are single-quoted.
assert_eq!(quotemeta("Hello, world"), "'Hello, world'");
// Unicode gets C-quoted.
assert_eq!(quotemeta("\u{1f980}"), r"$'\360\237\246\200'");
// It handles `Path`s
assert_eq!(quotemeta(Path::new("/etc/passwd")), "/etc/passwd");
Examples found in repository?
examples/cat.rs (line 5)
3
4
5
6
7
fn main() {
    for path in std::env::args_os().skip(1) {
        println!("cat {}", quotemeta(&path));
    }
}