#!/usr/bin/env perl
#
# Simple script that runs arguments with no output unless
# the arguments return non-zero.
#
# Simplifies the ever-common:
#
#   command > /dev/null 2>&1
#
# except that if 'command' errors, the stdout and stderr will
# be shown at that point.
#
#############################################################

my $output, $pid;

$pid = open( CHILD, "-|" );

if( $pid )
{
  # Parent
  local $/ = undef; # No line buffering, get all at next read
  $output = <CHILD>;
  if( ! close( CHILD ) )
  {
    # $! is non-zero if a system call failed during the close process (unlikely)
    die "$0: $ARGV[0]: $!\n" if $!;

    # Otherwise, non-zero exit status
    print $output;
    exit ($? >> 8);
  }
}
elsif( defined $pid )
{
  # Child
  open( STDERR, ">&STDOUT" ) or die "$0: dup: $!\n";

  exec( { $ARGV[0] } @ARGV ); # Shouldn't return

  die "$0: $ARGV[0]: $!\n"; # exec failed
}
else
{
  # Fork failed
  die "$0: fork: $!\n";
}

