Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a shell command

Tags:

shell

rust

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?

like image 747
Peiyuan Li Avatar asked Jul 28 '15 03:07

Peiyuan Li


People also ask

Which command is used to execute the shell script?

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.

What is shell execution?

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.

Can I run shell script in CMD?

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.


3 Answers

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 :)

like image 71
S.R Avatar answered Oct 17 '22 12:10

S.R


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.

like image 8
DK. Avatar answered Oct 17 '22 12:10

DK.


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");
like image 1
micoay Avatar answered Oct 17 '22 11:10

micoay