chronic: Flush output more often to better preserve stdout,err ordering.
[moreutils.git] / chronic
blobcb927b3a4322421dd15d7369269144717de934aa
1 #!/usr/bin/perl
3 =head1 NAME
5 chronic - runs a command quietly unless it fails
7 =head1 SYNOPSIS
9 chronic [-ev] COMMAND...
11 =head1 DESCRIPTION
13 chronic runs a command, and arranges for its standard out and standard
14 error to only be displayed if the command fails (exits nonzero or crashes).
15 If the command succeeds, any extraneous output will be hidden.
17 A common use for chronic is for running a cron job. Rather than
18 trying to keep the command quiet, and having to deal with mails containing
19 accidental output when it succeeds, and not verbose enough output when it
20 fails, you can just run it verbosely always, and use chronic to hide
21 the successful output.
23 0 1 * * * chronic backup # instead of backup >/dev/null 2>&1
24 */20 * * * * chronic -ve my_script # verbose for debugging
26 =head1 OPTIONS
28 =over 4
30 =item -v
32 Verbose output (distinguishes between STDOUT and STDERR, also reports RETVAL)
34 =item -e
36 Stderr triggering. Triggers output when stderr output length is non-zero.
37 Without -e chronic needs non-zero return value to trigger output.
39 =back
41 =head1 AUTHOR
43 Copyright 2010 by Joey Hess <id@joeyh.name>
45 Original concept and "chronic" name by Chuck Houpt.
46 Code for verbose and stderr trigger by Tomas 'Harvie' Mudrunka 2016.
48 Licensed under the GNU GPL version 2 or higher.
50 =cut
52 use warnings;
53 use strict;
54 use IPC::Run qw( start pump finish timeout );
55 use Getopt::Std;
57 our $opt_e = 0;
58 our $opt_v = 0;
59 getopts('ev'); # only looks at options before the COMMAND
61 if (! @ARGV) {
62 die "usage: chronic COMMAND...\n";
65 my ($out, $err);
66 my $h = IPC::Run::start \@ARGV, \*STDIN, \$out, \$err;
67 $h->finish;
68 my $ret=$h->full_result;
70 if ($ret >> 8) { # child failed
71 showout();
72 exit ($ret >> 8);
74 elsif ($ret != 0) { # child killed by signal
75 showout();
76 exit 1;
78 elsif ($opt_e && (length($err) > 0)) {
79 showout();
80 exit 2;
82 else {
83 exit 0;
86 sub showout {
87 print "STDOUT:\n" if $opt_v;
88 print STDOUT $out;
89 STDOUT->flush();
90 print "\nSTDERR:\n" if $opt_v;
91 print STDERR $err;
92 STDERR->flush();
93 print "\nRETVAL: ".($ret >> 8)."\n" if $opt_v;