When running shell commands, how do I pass in str in it?

use std::process::Command;

fn main()
{
    let some_text = "Testing 123";
    let mut output = Command::new("sh");
    output.arg("-c").arg("echo Testing 123 | lemonbar -p");
    output.status().expect("Error!");
}

I want to pass some_text variable and feed it into lemonbar. Currently this code works just fine. Bu if I write it as output.arg("-c").arg("echo {} | lemonbar -p", some_text); I will have some error. Any idea how to write it in such a way that it works?

You can use the format! macro.

use std::process::Command;

fn main()
{
    let some_text = "Testing 123";
    let mut output = Command::new("sh");
    output.arg("-c").arg(&format!("echo {} | lemonbar -p", some_text));
    output.status().expect("Error!");
}

Of course, keep escaping in mind.

1 Like

output.arg("-c").arg(&format!("echo {} | lemonbar -p", some_text)); Why does the format!() macro need to be used as a reference (as you used & symbol)?

Ah, I guessed that .arg takes a &str as an argument, and since format! returns a String, I had to convert it. However it turns out to be a generic function defined as

pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command

and both String and &str implement the AsRef<OsStr> trait, so it turns out to not make any difference. It works both with and without the &.

2 Likes

There are also some crates available that can make your life easier. For example this one:
https://github.com/synek317/shellfn

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.