Execute a shell command

2019-06-16 18:40发布

I want to execute a shell command in Rust. In Python I can do this:

import os
cmd = r'echo "test" >> ~/test.txt'
os.system(cmd)

But Rust only has std::process::Command. How can I execute a shell command like cd xxx && touch abc.txt?

标签: shell rust
2条回答
一纸荒年 Trace。
2楼-- · 2019-06-16 19:14

You should really avoid system. What it does depends on what shell is in use and what operating system you're on (your example almost certainly won't do what you expect on Windows).

If you really, desperately need to invoke some commands with a shell, you can do marginally better by just executing the shell directly (like using the -c switch for bash).

If, for some reason, the above isn't feasible and you can guarantee your program will only run on systems where the shell in question is available and users will not be running anything else...

...then you can just use the system call from libc just as you would from regular C. This counts as FFI, so you'll probably want to look at std::ffi::CStr.

查看更多
男人必须洒脱
3楼-- · 2019-06-16 19:23

Everybody is looking for:

use std::process::Command;

fn main() {
    let output = Command::new("echo")
        .arg("Hello world")
        .output()
        .expect("Failed to execute command");

    assert_eq!(b"Hello world\n", output.stdout.as_slice());
}

For more information and examples, see the docs.

You wanted to simulate &&. std::process::Command has a status method that returns a Result<T> and Result implements and_then. You can use and_then like a && but in more safe Rust way :)

查看更多
登录 后发表回答