How do I check if a Perl script is running in a terminal?

mscha picture mscha · Aug 5, 2011 · Viewed 10.7k times · Source

I'm trying to determine, within a Perl script on Linux, whether it's running in a terminal.

That is, I need code that:

  • returns true when simply running on the command-line
  • also returns true when running ./myscript.pl | less or even ./myscript.pl </dev/null >/dev/null 2>/dev/null
  • returns false when running in a cron job, or as a CGI script

Especially because of the second bullet, I can't use -t STDOUT and variations, and also IO::Interactive is of no use.

The information does appear to be available. If I run ps, it shows an entry like pts/2 in the TTY column, even when I run ./myscript.pl </dev/null >/dev/null 2>/dev/null, and ? when running as a cron job or CGI script.

Is there an elegant way to determine this in a Perl script? I'd rather not have to parse the output of ps.

Answer

Ingo picture Ingo · Aug 5, 2011

You can try to open /dev/tty. This will work if you are in a terminal (even in a terminal on a remote computer). Otherwise, if the script is run via at or cron, it won't.

Note: this will only work on Unix systems.