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
?
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
?
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 fromlibc
just as you would from regular C. This counts as FFI, so you'll probably want to look atstd::ffi::CStr
.Everybody is looking for:
For more information and examples, see the docs.
You wanted to simulate
&&
.std::process::Command
has astatus
method that returns aResult<T>
andResult
implementsand_then
. You can useand_then
like a&&
but in more safe Rust way :)