diff --git a/commandtest/.gitignore b/commandtest/.gitignore new file mode 100644 index 0000000..bafe1c9 --- /dev/null +++ b/commandtest/.gitignore @@ -0,0 +1 @@ +script.log diff --git a/commandtest/Cargo.toml b/commandtest/Cargo.toml new file mode 100644 index 0000000..cc9c4c7 --- /dev/null +++ b/commandtest/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "commandtest" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/commandtest/README.md b/commandtest/README.md new file mode 100644 index 0000000..1850d52 --- /dev/null +++ b/commandtest/README.md @@ -0,0 +1,5 @@ +# CommandTest + +Playing a bit with `Command`, trying to send the output of a command to a file +(easy) while capturing it at the same time, looking for some special strings +(hard). diff --git a/commandtest/src/main.rs b/commandtest/src/main.rs new file mode 100644 index 0000000..53aea2d --- /dev/null +++ b/commandtest/src/main.rs @@ -0,0 +1,32 @@ +use std::ffi::OsString; +use std::fs::File; +use std::path::PathBuf; +use std::process::Command; + +fn search_in_path(name: &str) -> Option { + let path = std::env::var_os("PATH").unwrap_or_else(OsString::new); + std::env::split_paths(&path).find_map(|dir| { + let full_path = dir.join(name); + if full_path.is_file() { + Some(full_path) + } else { + None + } + }) +} + +fn main() { + // this requires always running with `cargo run` + let base = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let log_file = File::create("script.log").unwrap(); + let the_script = base.join("src").join("the_script.sh"); + let bash = search_in_path("bash").unwrap(); + + let mut cmd = Command::new(bash) + .arg(the_script) + .stdout(log_file) + .spawn() + .unwrap(); + + cmd.wait().unwrap(); +} diff --git a/commandtest/src/the_script.sh b/commandtest/src/the_script.sh new file mode 100755 index 0000000..ff7d534 --- /dev/null +++ b/commandtest/src/the_script.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash + +echo "Hello, I'm a script!" +echo "I write stuff in the output." +echo "Everything should go to a file." +echo "But also, you need to capture this:" +echo "WARNING: This is a warning" +echo " It continues if the line starts with spaces" +echo " And keeps going till there are no more spaces-prefixes" +echo "Like this." +echo "Then you're good to go."