Hey,
new to rust, so I'm playing around with it
I have a vec of Strings that represent shell commands. I want to iterate over them and execute them one by one. While I have "something" running, I'm sure a) it's not idiomatic and b) it's not working for every case (see the last two, where I'm redirecting output/piping).
How can I improve my code?
use std::process::Command;
fn main() {
let commands = vec![
"ls -lah".to_string(),
"echo 'this is a really long string'".to_string(),
"echo 'hello world > file.txt".to_string(),
"cat file.txt | grep hello".to_string(),
];
let commands_iterator = commands.into_iter();
commands_iterator.for_each(|cmd| {
println!("---------");
println!("{}", cmd);
let mut cmd_parts = cmd.split(" ");
let mut c = Command::new("");
if let Some(a) = cmd_parts.next() {
println!("{:?}", a);
c = Command::new(a);
}
cmd_parts.for_each(|part| {
println!("> {}", part);
c.arg(part);
});
c.status().expect("failed to execute process");
});
}
The output:
---------
ls -lah
"ls"
> -lah
total 20K
drwxr-xr-x 1 runner runner 104 May 19 08:38 .
drwxrwxrwx 1 runner runner 68 May 19 08:00 ..
drwxr-xr-x 1 runner runner 12 Oct 8 2021 .cache
-rw-r--r-- 1 runner runner 154 Oct 16 2021 Cargo.lock
-rw-r--r-- 1 runner runner 200 Dec 17 2021 Cargo.toml
-rw-r--r-- 1 runner runner 144 Apr 23 18:29 .replit
-rw-r--r-- 1 runner runner 25 Apr 24 14:20 replit.nix
drwxr-xr-x 1 runner runner 14 May 19 08:39 src
drwxr-xr-x 1 runner runner 66 Apr 12 23:55 target
---------
echo 'this is a really long string'
"echo"
> 'this
> is
> a
> really
> long
> string'
'this is a really long string'
---------
echo 'hello world > file.txt
"echo"
> 'hello
> world
> >
> file.txt
'hello world > file.txt
---------
cat file.txt | grep hello
"cat"
> file.txt
> |
> grep
> hello
cat: file.txt: No such file or directory
cat: '|': No such file or directory
cat: grep: No such file or directory
cat: hello: No such file or directory
Any help appreciated