Output shell history data by using process::Command?

Hi, Rustaceans

I just started to learn Rust.

my question is : how to get a shell history data, like
history -i | grep "$(date -v-1d +%F)" > exported-history.txt
by using process::Command ?

history doesn't have -i option, did you mean history | grep -i ...?

Because history is a shell builtin, you have to spawn a shell. The output can be obtained via Command::output method:

use std::process::Command;
fn main() {
    let your_command = "pwd";
    let output = Command::new("bash")
        .output().expect("cannot spawn bash")
    println!("{}", String::from_utf8(output).expect("Output is not utf-8"));

... But bash -lc "history" doesn't work for some reason I don't understand. I suggest to parse the .bash_history file instead of spawning a shell.

you're right, I just realized that -i flag is actually from Zsh shell ( -i used for displaying history's date & time, my intention is to get history data based on dates ).

I slightly adjust your_command from your codes, it does output exported-history.txt successfully, but the file still contains nothing.

    let your_command = "history > exported-history.txt";

while history > exported-history.txt run normally in terminal, I have no idea why it's not behave the same via process::Command.

you're creating a new instance of the shell and then exporting its command history, which will be empty
(it looks like the history command, at least in bash, will only print the current session history and not the stored history from ~/.bash_history)

hmm, interesting. I'm wondering is there anyway to workaround on this issue.

besides reading the history file yourself ? i doubt it, at least, you can't 'call back' into the parent shell (if any) that launched your program

I get the whole history, not the session history when I type history in a shell. But typing bash -c history doesn't output anything. That is the mystery. I first thought it was due to being a login shell or not but -l didn't help.

Edit: scanned the bash code a bit. Maybe the issue is due to the shell not using readline when spawned? Not sure there is a way to change this behavior.

Edit: finally solved the problem by using echo history | bash -i command. The interactive shell was needed (and -c cannot be used as it cancels -i).

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.