Log a Terminal Session

Records everything shown in a shell session to a timestamped log file, with terminal escape codes (colors, cursor movement) stripped and every line prefixed with the time it was written. Useful for keeping a record of what you ran and what it printed, for example during an engagement or a long debugging session.

mkdir -p "/PATH-TO-LOGS" && LOGFILE="/PATH-TO-LOGS/$(date +%Y%m%d_%H%M%S)_terminal_session.log" && echo "[$(date '+%Y-%m-%d %H:%M:%S')] Terminal logging started -> $LOGFILE" && script -f -q -c "$SHELL" >(gawk '{gsub(/\033\[[0-9;?]*[A-Za-z]/,"");gsub(/\033\][^\033\007]*(\007|\033\\)/,"");gsub(/\033[()][0-9A-Za-z]/,"");gsub(/\r/,"");printf "[%s] %s\n",strftime("%Y-%m-%d %H%M%S"),$0;fflush()}' >> "$LOGFILE")

Replace /PATH-TO-LOGS with a folder you control.

What it does

  • mkdir -p and LOGFILE=... create the log folder and a name like 20261009_134500_terminal_session.log.
  • script -f -q -c "$SHELL" FILE runs a fresh shell and writes the session to FILE. -f flushes after every write so the log is current if the session dies, and -q suppresses the start/stop banners.
  • >(...) is process substitution: instead of a file, script writes to a gawk process that cleans each line and appends it to $LOGFILE.
  • The three gsub calls strip ANSI escape sequences, the fourth strips carriage returns, and strftime stamps each line.

Needs

  • bash or zsh (process substitution; plain sh/dash won’t parse it)
  • gawk specifically (strftime is a gawk extension, not in mawk)
  • Linux script from util-linux (-c and -f). macOS’s BSD script takes different flags.

Stop logging

Type exit (or press Ctrl+D) to leave the logged shell and return to your normal one.

Watch the log live from another terminal

tail -f /PATH-TO-LOGS/*_terminal_session.log

Caution

The log captures anything printed to the screen, including secrets you echo or paste into a command. Treat the log folder as sensitive, and keep it out of any repo.