How to know if you’re in a typescript

typescript

I'm using the script command to save all the output from the terminal to a file called typescript. Or script foo to save to the file foo.

Now, let's say I'm going along typing command after command and I forget whether or not I'm in a typescript or not.

How can I find out if I'm within a typescript or not?

Best Answer

Maybe with:

if lsof -tac script "$(tty)" > /dev/null; then
  echo "I'm running under script"
else
  echo "I'm not"
fi

You could add something like:

lsof -tac script "$(tty)" > /dev/null && PS1="[script] $PS1"

To your ~/.zshrc or ~/.bashrc, so the information on whether you're in script or not would be visible on your shell prompt.

Alternatively, if you can't guarantee that lsof be installed you could do (assuming an unmodified IFS):

terminal=$(ps -o comm= -p $(ps -o ppid= -p $(ps -o sid= -p "$$")))
[ "$terminal" = script ] && PS1="[script] $PS1"

The heuristic is to get the command name of the parent of the session leader which generally would be the terminal emulator (xterm, script, screen...).