]> ruderich.org/simon Gitweb - config/dotfiles.git/blob - bin/chronic
a9fa47b8f45b3bd3608527131e60ffc1395b8baa
[config/dotfiles.git] / bin / chronic
1 #!/usr/bin/perl
2
3 =head1 NAME
4
5 chronic - runs a command quietly unless it fails
6
7 =head1 SYNOPSIS
8
9 chronic COMMAND...
10
11 =head1 DESCRIPTION
12
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.
16
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.
22
23         0 1 * * * chronic backup # instead of backup >/dev/null 2>&1
24
25 =head1 AUTHOR
26
27 Copyright 2010 by Joey Hess <joey@kitenet.net>
28
29 Original concept and "chronic" name by Chuck Houpt.
30
31 Licensed under the GNU GPL version 2 or higher.
32
33 =cut
34
35 use warnings;
36 use strict;
37 use IPC::Run qw( start pump finish timeout );
38
39 if (! @ARGV) {
40         die "usage: chronic [-l LOGFILE] COMMAND...\n";
41 }
42
43 my $logfile;
44 if (@ARGV >= 3 and $ARGV[0] eq '-l') {
45         $logfile = $ARGV[1];
46         shift @ARGV;
47         shift @ARGV;
48 }
49
50 my ($out, $err);
51 my $h = IPC::Run::start \@ARGV, \*STDIN, \$out, \$err;
52 $h->finish;
53 my $ret=$h->full_result;
54
55 if (defined $logfile) {
56         open my $fh, '>', $logfile
57                 or showout_and_die("failed to open logfile '$logfile'");
58         print $fh $err; # stderr is more interesting, show it first
59         print $fh $out;
60         close $fh
61                 or showout_and_die("failed to close logfile '$logfile'");
62 }
63
64 if ($ret >> 8) { # child failed
65         showout();
66         exit ($ret >> 8);
67 }
68 elsif ($ret != 0) { # child killed by signal
69         showout();
70         exit 1;
71 }
72 else {
73         exit 0;
74 }
75
76 sub showout {
77         print STDOUT $out;
78         print STDERR $err;
79 }
80 sub showout_and_die {
81         my $errno = $!;
82         showout();
83         die "chronic: $_[0]: $errno\n";
84 }