releasing package moreutils version 0.68
[moreutils.git] / chronic
blob43e8693588449b2fd95cc9ca6d3eb31b53584ad2
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 In this mode, chronic's return value will be C<2> if the command's return
40 value is C<0> but the command printed to stderr.
42 =back
44 =head1 AUTHOR
46 Copyright 2010 by Joey Hess <id@joeyh.name>
48 Original concept and "chronic" name by Chuck Houpt.
49 Code for verbose and stderr trigger by Tomas 'Harvie' Mudrunka 2016.
51 Licensed under the GNU GPL version 2 or higher.
53 =cut
55 use warnings;
56 use strict;
57 use IPC::Run qw( start pump finish timeout );
58 use Getopt::Std;
60 our $opt_e = 0;
61 our $opt_v = 0;
62 getopts('ev'); # only looks at options before the COMMAND
64 if (! @ARGV) {
65 die "usage: chronic COMMAND...\n";
68 my ($out, $err);
69 my $h = IPC::Run::start \@ARGV, \*STDIN, \$out, \$err;
70 $h->finish;
71 my $ret=$h->full_result;
73 if ($ret >> 8) { # child failed
74 showout();
75 exit ($ret >> 8);
77 elsif ($ret != 0) { # child killed by signal
78 showout();
79 exit 1;
81 elsif ($opt_e && (length($err) > 0)) {
82 showout();
83 exit 2;
85 else {
86 exit 0;
89 sub showout {
90 print "STDOUT:\n" if $opt_v;
91 print STDOUT $out;
92 print "\nSTDERR:\n" if $opt_v;
93 STDOUT->flush();
94 print STDERR $err;
95 STDERR->flush();
96 print "\nRETVAL: ".($ret >> 8)."\n" if $opt_v;