Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 5 down vote accepted

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

share|improve this answer

Interesting problem. I found a small bash script could do the job pretty reliably:

#!/bin/bash

PP=$(ps -o ppid= $$)

while [[ $PP != 1 ]]
do
    LINE=$(ps -o ppid= -o comm= $PP | sed 's/^  *//')
    COMM=${LINE#* }
    PP=${LINE%% *}
    if [[ $COMM == script ]]  # Might need a different comparison
    then
        echo "In script"
        exit 0
    fi
done
echo "Not in script"

I think this is slightly different than proposed by Stephane Chazelas, in that my script works its way up the parent:child relationship that Linux/Unix processes have until it finds PID 1, or it finds "script" as the process.

share|improve this answer
2  
Interesting approach. However, note that if for instance, you start an xterm from your script session, that script will thing the shell in that xterm is running under script. Well it is in a way, but the output is not going to the typescript. My approach checks the terminal associated with the current session so would not have that issue. –  Stéphane Chazelas Mar 20 '13 at 18:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.