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
?
3. Execute Shell Script Using . ./ (dot space dot slash) While executing the shell script using “dot space dot slash”, as shown below, it will execute the script in the current shell without forking a sub shell.
Shell is a command-line interpreter that allows the user to interact with the system. It is responsible for taking inputs from the user and displaying the output. Shell scripts are a series of commands written in order of execution. These scripts can contain functions, loops, commands, variables.
Open Command Prompt and navigate to the folder where the script file is available. Type Bash script-filename.sh and hit the enter key. It will execute the script, and depending on the file, you should see an output.
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 :)
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
.
For anyone looking for a way to set the current directory for the subprocess running the command i. e. run "ls" in some dir there's Command::current_dir
. Usage:
use std::process::Command;
Command::new("ls")
.current_dir("/bin")
.spawn()
.expect("ls command failed to start");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With