On Mon, Feb 05, 2024 at 12:28:38AM +0000, Gareth Evans wrote:
> I was trying to view the history of commands run during a script session.
> 
> user@qwerty:~$ script foo
> Script started, output log file is 'foo'.
> user@qwerty:~$ date
> Mon  5 Feb 00:21:16 GMT 2024
> user@qwerty:~$ exit
> exit
> Script done.
> user@qwerty:~$ history |tail -n3
> 30914  2024-02-04 23:44:24  man script
> 30915  2024-02-05 00:21:15  script foo
> 30916  2024-02-05 00:21:25  history |tail -n3 # NB "date" is missing
> 
> Michael Grant pointed out (among other things) that the history is available, 
> but not in the terminal in which script has just exited.

OK.  Well, start by thinking about what happens if you're in a bash
shell, and you type "bash".  You get a second bash instance, which is a
child process of the original shell.  The original shell goes to sleep,
and waits for the child to exit.

When the child process starts up, it reads the .bash_history file (unless
you changed the variable that names the file), thereby loading the shell
history from disk into memory.  Then you run whatever commands you run,
and those are appended to the in-memory shell history.  Then you exit,
at which point bash rewrites the .bash_history file.

After exiting from the child shell, you're back in the original shell.
The original shell's in-memory history did not change during the child's
lifetime.  The only change to the in-memory history is the addition of
a "bash" command.  The .bash_history file has been changed, but the
running shell doesn't read that to get the new contents in memory.

If/when you exit from the original shell, the .bash_history file will
be rewritten again, using the in-memory history of the original bash
instance.  This does *not* include any changes that were written by
the child process.  Those changes may simply be lost.  It depends on
which history options you've chosen, and how many new commands were
appended to the original shell's in-memory history before exiting.

Once you understand all of this, then it should be obvious how "script"
works.  It runs a new instance of "bash".  As far as history goes, it
works exactly like the above.  The only difference is you've also got
a file containing a recording of the terminal session.

If you're one of these "I want every command I ever run to be in my
shell history, retained forever, and I don't care how much space it
takes" people, then there are web pages out there that can help you.
I don't follow that philosophy myself, so I can't give you specific
variables and settings.  But Google can.

Reply via email to