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?

  • What is the terminal history of a script? It's output? Would redirecting it to a file with my_script > output.txt be enough? – nohillside Dec 12 '17 at 13:19
  • @patrix My script has a main menu. If the user enters some option, it produces an output. I would like to include an option in the main menu that saves whatever that is on screen to a text file, I meant. Hope that makes it clearer! – Ali Gul Dec 12 '17 at 13:23
  • @patrix Basically, the current session. – Ali Gul Dec 12 '17 at 14:18
  • "Session", "history" and "content of current screen" are three different things. If you want to have the same as the Export Text as function, it's definitively more than what's on screen :-) – nohillside Dec 12 '17 at 16:20

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
$ 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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .