Redirect Output to stderr

1k views Asked by At

I want to redirect my output to stderr. I have a cron job

function auth_tester {
  cd /data/$1/current && bundle exec rake 'authentication:tester' 1>    /dev/null
}

which calls a rake task

namespace :authentication do

  desc "Automatically runs authentication tester and notifies in case of failure"
  task :tester => :environment do
    auth_tester_results = AuthenticationTester.perform

    exit(auth_tester_results.success? ? 0 : 1)
  end
end

If the 'auth_tester_results' boolean is a false I want to redirect the output to stderr. How can it be done?

2

There are 2 answers

1
Aleksei Matiushkin On

Since you are already dealing with shell, do it in shell:

function auth_tester {
  cd /data/$1/current && \
  bundle exec rake 'authentication:tester' >/dev/null 2>&1
  #                                 HERE:  ⇑⇑⇑⇑⇑⇑⇑⇑⇑⇑⇑⇑⇑⇑⇑
}

stderr has an id = 2, and we are redirecting stdout to /dev/null, and stderr to stdout, eventually redirecting it to /dev/null.

To redirect stdout to stderr, use the opposite:

1>&2

To redirect the output from ruby, one uses proper receiver with IO#puts:

$stderr.puts "Goes to stderr"
0
Aaron Thomas On

Sending output to STDERR can be done via print or puts. Here I opt to send to STDERR rather than $stderr, but this will work for either:

STDERR.puts 'my message here'

If you'd like to change the exit status of your Ruby script (to show the script did not finish successfully, for example) you can use exit with a parameter of false:

exit(false)

To both send output to STDERR and return an unsuccessful exit status, you can use abort:

abort 'my message here'



For additional information, ref this article from honeybadger.io.