MacOS – Save Mac Terminal session to text file

bashmacosterminal

Is there a way of saving the terminal history of a script to file? I know I can do this by Shell > Export Text As… but is there a command (Bash) to do this?

Best Answer

This can be done with the standard unix command script(1) though requires running a subshell under the current shell. That is, start a terminal, and run script, issue whatever commands need to be logged, then exit from that shell:

$ script
Script started, output file is typescript
$ uptime
11:30  up 22 days, 16:15, 1 user, load averages: 1.43 1.37 1.38
$ exit

Script done, output file is typescript
$ 

Then in the output typescript file there should be a record of the shell session run under script(1).

But wait, there's more! With expect one can also save a session and possibly replay it. This requires installing expect from a ports system (Fink, Homebrew, or here MacPorts) which should install autoexpect:

$ port installed | grep expect
  expect @5.45.3_0 (active)
$ which autoexpect
/opt/local/bin/autoexpect
$ autoexpect $SHELL
autoexpect started, file is script.exp
$ uptime
 6:47  up 23 days, 11:32, 1 user, load averages: 1.37 1.39 1.33
$ exit
autoexpect done, file is script.exp
$ 

Doing something useful with script.exp in turn probably requires knowledge of expect and TCL, so this is a more advanced option. (expect in particular has a log_file option that can be toggled to save everything, but then you'd be writing everything in TCL and not bash...)

Otherwise the terminal itself must save the session; iTerm.app probably has more options for this (Session -> Log -> Start) than Terminal.app.