How to automatically save the output of the last command that I ran (every time)?

If I wanted to get the output of the last command stored in a file, for example ~/.last_command.txt(overwriting the output of the previous command), how could I do this in bash so that the output goes to both stdout and this file? I assume that this will be connected with connecting to tee ~/.last_command.txt, but I don’t know what to do, and I definitely don’t want to add this to every command that I run manually.

Also, how can I extend this to save the output of the last n commands?

+4
source share
4 answers

In bash, this seems to have the desired effect.

bind 'RETURN: "|tee ~/.last_command.txt\n"'

bashrc, .

, . , :

matt@devpc:$ |tee ~/.last_command.txt
bash: syntax error near unexpected token `|'

, .

+1

/, TTY, ...

exec 4>&1
PROMPT_COMMAND="exec 1>&4; exec > >(mv ~/.last_command{_tmp,}; tee ~/.last_command_tmp)"

, :

exec > >(tee ~/.commands)
0

( ) "" :

<...login...>
% bash | tee -a ~/.bash_output
% ls  # this is the nested shell
% exit
% cat ~/.bash_output
% exit

. shell /etc/passwd bash bash | tee -a ~USERNAME/.bash_output.

0

1:

script -c ls ~/.last_command.txt

1 :

$ script ~/.last_command.txt
$ command1
$ command2
$ command3
$ exit

If you want to save for 1 login session, add a "script" to .bashrc

0
source

All Articles