1

I have a script with a line like this:

$foo = $bar if -t;

Near as I can tell, this is saying,

  1. if this script is run from a terminal, set $foo to $bar.

  2. If this script was run from cron, that would evaluate to false.

Have I got this right?

Lucky
  • 627
  • 5
  • 15
  • 3
    Always read the perldoc (https://perldoc.perl.org/functions/-X) before asking questions. – Jim Garrison Jan 18 '22 at 18:49
  • I'm asking for clarification on the documentation. – Lucky Jan 18 '22 at 19:04
  • 1
    @Lucky Then maybe you should mention that you want a clarification on the documentation. – TLP Jan 18 '22 at 19:06
  • 1
    The documentation is pretty clear, and you could always write a 3-line script and run it from cron to see what happens. That would likely answer your question faster than posting here. – Jim Garrison Jan 18 '22 at 19:13
  • https://stackoverflow.com/questions/20332218/what-is-the-t-used-for-in-this-perl-code – TLP Jan 18 '22 at 19:27

2 Answers2

3

In perldoc perlfunc for the collection of functions called -X, you can read:

-t  Filehandle is opened to a tty.

Also

If the argument is omitted, tests $_, except for -t, which tests STDIN. 

Which is to say your code does -t STDIN.

TLP
  • 66,756
  • 10
  • 92
  • 149
  • So its asking if the script if its having input piped to it? – Lucky Jan 18 '22 at 19:06
  • @Lucky When I am testing it, it returns true if STDIN is not active, and if I am piping input to perl it returns false. – TLP Jan 18 '22 at 19:20
  • @Lucky If I were to guess, someone might be trying to find out whether the program is reading from STDIN or from ARGV? The context might give you some clues, what is the $foo and $bar variables doing? – TLP Jan 18 '22 at 19:29
  • 2
    @Lucky Re "*So its asking if the script if its having input piped to it?*", No. Plain files, sockets and non-TTY devices also aren't TTYs. – ikegami Jan 18 '22 at 20:00
1

The -t file test is documented in perlfunc, although you get to by looking up -X instead of the specific file test:

% perldoc -f -X

Depending on your task, IO::Interactive may do the job better since there can be a few gotchas with figuring out if something is truly interactive.

If you want to know that you are running under cron (and not non-interactive in some other way), you might consider have a variable set in your crontab (or using one already set) and simply looking for it. In your crontab:

IN_CRON=1

Then, in the script:

do_something() if $ENV{IN_CRON};
brian d foy
  • 129,424
  • 31
  • 207
  • 592