How to know if you're in a typescript?
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
...).
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.