-
Notifications
You must be signed in to change notification settings - Fork 1
/
chronic
executable file
·97 lines (70 loc) · 2.13 KB
/
chronic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#!/usr/bin/perl
=head1 NAME
chronic - runs a command quietly unless it fails
=head1 SYNOPSIS
chronic [-ev] COMMAND...
=head1 DESCRIPTION
chronic runs a command, and arranges for its standard out and standard
error to only be displayed if the command fails (exits nonzero or crashes).
If the command succeeds, any extraneous output will be hidden.
A common use for chronic is for running a cron job. Rather than
trying to keep the command quiet, and having to deal with mails containing
accidental output when it succeeds, and not verbose enough output when it
fails, you can just run it verbosely always, and use chronic to hide
the successful output.
0 1 * * * chronic backup # instead of backup >/dev/null 2>&1
*/20 * * * * chronic -ve my_script # verbose for debugging
=head1 OPTIONS
=over 4
=item -v
Verbose output (distinguishes between STDOUT and STDERR, also reports RETVAL)
=item -e
Stderr triggering. Triggers output when stderr output length is non-zero.
Without -e chronic needs non-zero return value to trigger output.
In this mode, chronic's return value will be C<2> if the command's return
value is C<0> but the command printed to stderr.
=back
=head1 AUTHOR
Copyright 2010 by Joey Hess <id@joeyh.name>
Original concept and "chronic" name by Chuck Houpt.
Code for verbose and stderr trigger by Tomas 'Harvie' Mudrunka 2016.
Licensed under the GNU GPL version 2 or higher.
=cut
use warnings;
use strict;
use IPC::Run qw( start pump finish timeout );
use Getopt::Std;
our $opt_e = 0;
our $opt_v = 0;
getopts('ev'); # only looks at options before the COMMAND
if (! @ARGV) {
die "usage: chronic COMMAND...\n";
}
my ($out, $err);
my $h = IPC::Run::start \@ARGV, \*STDIN, \$out, \$err;
$h->finish;
my $ret=$h->full_result;
if ($ret >> 8) { # child failed
showout();
exit ($ret >> 8);
}
elsif ($ret != 0) { # child killed by signal
showout();
exit 1;
}
elsif ($opt_e && (length($err) > 0)) {
showout();
exit 2;
}
else {
exit 0;
}
sub showout {
print "STDOUT:\n" if $opt_v;
print STDOUT $out;
print "\nSTDERR:\n" if $opt_v;
STDOUT->flush();
print STDERR $err;
STDERR->flush();
print "\nRETVAL: ".($ret >> 8)."\n" if $opt_v;
}