bash_read/
bash_read.rs

1use rexpect::error::Error;
2use rexpect::spawn_bash;
3
4fn main() -> Result<(), Error> {
5    let mut p = spawn_bash(Some(2000))?;
6
7    // case 1: wait until program is done
8    p.send_line("hostname")?;
9    let hostname = p.read_line()?;
10    p.wait_for_prompt()?; // go sure `hostname` is really done
11    println!("Current hostname: {hostname}");
12
13    // case 2: wait until done, only extract a few infos
14    p.send_line("wc /etc/passwd")?;
15    // `exp_regex` returns both string-before-match and match itself, discard first
16    let (_, lines) = p.exp_regex("[0-9]+")?;
17    let (_, words) = p.exp_regex("[0-9]+")?;
18    let (_, bytes) = p.exp_regex("[0-9]+")?;
19    p.wait_for_prompt()?; // go sure `wc` is really done
20    println!("/etc/passwd has {lines} lines, {words} words, {bytes} chars");
21
22    // case 3: read while program is still executing
23    p.execute("ping 8.8.8.8", "bytes of data")?; // returns when it sees "bytes of data" in output
24    for _ in 0..5 {
25        // times out if one ping takes longer than 2s
26        let (_, duration) = p.exp_regex("[0-9. ]+ ms")?;
27        println!("Roundtrip time: {duration}");
28    }
29    p.send_control('c')?;
30    Ok(())
31}