Search code examples
rubyrakecommand-line-interface

Can ruby tell if it is called from an interactive shell or cron?


When I run a rake task by hand, I want to make Rails.logger log to STDOUT. But not if the rake task is run by a cron job. Is there a way to find out, how the rake task got started?

task :my_env => :environment do
  if A_USER_IS_WATCHING_ME
    Rails.logger = Logger.new(STDOUT)
    ActiveRecord::Base.logger = Logger.new(STDOUT)
  end
end

Solution

  • $stdout.tty? returns true if $stdout is associated with a terminal device (i.e. an interactive user) and false otherwise:

    # test.rb
    if $stdout.tty?
      puts "tty"
    else
      puts "not a tty"
    end
    

    From bash:

    $ ruby test.rb
    tty
    
    $ ruby test.rb > test.log
    $ cat test.log
    not a tty