Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does stdout get stored somewhere in the filesystem or in memory? [duplicate]

Tags:

shell

stdout

zsh

I know I can save the result of a command to a variable using last_output=$(my_cmd) but what I'd really want is for $last_output to get updated every time I run a command. Is there a variable, zsh module, or plugin that I could install?

I guess my question is does stdout get permanently written somewhere (at least before the next command)? That way I could manipulate the results of the previous command without having to re-run it. This would be really useful for commands that take a long time to run

like image 925
nachocab Avatar asked Mar 21 '23 04:03

nachocab


1 Answers

If you run the following:

exec > >(tee save.txt)
# ... stuff here...
exec >/dev/tty

...then your stdout for everything run between the two commands will go both to stdout, and to save.txt.

You could, of course, write a shell function which does this for you:

with_saved_output() {
  "$@" \
  2> >(tee "$HOME/.last-command.err >&2) \
  | tee "$HOME/.last-command.out"
}

...and then use it at will:

with_saved_output some-command-here

...and zsh almost certainly will provide a mechanism to wrap interactively-entered commands. (In bash, which I can speak to more directly, you could do the same thing with a DEBUG trap).


However, even though you can, you shouldn't do this: When you split stdout and stderr into two streams, information about the exact ordering of writes is lost, even if those streams are recombined later.

Thus, the output

O: this is written to stdout first
E: this is written to stderr second

could become:

E: this is written to stderr second
O: this is written to stdout first

when these streams are individually passed through tee subprocesses to have copies written to disk. There are also buffering concerns created, and differences in behavior caused by software which checks whether it's outputting to a TTY and changes its behavior (for instance, software which turns color-coded output on when writing directly to console, and off when writing to a file or pipeline).

like image 141
Charles Duffy Avatar answered Apr 06 '23 05:04

Charles Duffy