Home > Software design >  use stdout of a process as a command in bash
use stdout of a process as a command in bash

Time:07-15

I have a rust script that prints something with a newline character at the end. I would like that line to be launched in bash instead of only being printed out. It acts as:

echo "my_line"

while I just want

my_line

as I would type it regularly in a terminal.

How would one achieve this and would it also be possible for a backgrounded process without a terminal open?

CodePudding user response:

You need

$(echo "my_line")

to execute the command after command substitution. Check https://www.gnu.org/software/bash/manual/html_node/Command-Substitution.html.

CodePudding user response:

You should use command substitution if possible, but there are times when you need things to be interpreted by the shell instead, like conditionals, redirects, or shell variables (cmd1 && cmd2, cmd > file, $var). If that is the case, then you should create a subprocess in Rust. This will spawn Bash, then tell it to run whatever is in command_string. Note that the command string parameter is a single string, and should not be split into vectored args:

use std::process::Command;
use std::thread;

fn main() {
    let command_string = "sleep 3 && echo done";

    let out = Command::new("bash")
        .args(["-c", command_string])
        .output()
        .expect("failed to run command")
        .stdout;
    println!("{}", String::from_utf8(out).unwrap());
}
  • Related