pee.1: Document difference with tee in stdout.
[moreutils.git] / zrun
blob7776db2d94f0d91a7783eab259ed9283f8c1703e
1 #!/usr/bin/perl
3 =head1 NAME
5 zrun - automatically uncompress arguments to command
7 =head1 SYNOPSIS
9 zrun command file.gz [...]
11 =head1 DESCRIPTION
13 Prefixing a shell command with "zrun" causes any compressed files that are
14 arguments of the command to be transparently uncompressed to temp files
15 (not pipes) and the uncompressed files fed to the command.
17 This is a quick way to run a command that does not itself support
18 compressed files, without manually uncompressing the files.
20 =head1 BUGS
22 Modifications to the uncompressed temporary file are not fed back into the
23 input file, so using this as a quick way to make an editor support
24 compressed files won't work.
26 =head1 AUTHOR
28 Copyright 2006 by Chung-chieh Shan <ccshan@post.harvard.edu>
30 =cut
32 use warnings;
33 use strict;
34 use IO::Handle;
35 use File::Spec;
36 use File::Temp qw{tempfile};
38 my $program = shift;
40 if (! @ARGV) {
41 die "Usage: zrun <command> <args>\n";
44 my @argument;
45 my %child;
46 foreach my $argument (@ARGV) {
47 if ($argument =~ m{^(.*/)?([^/]*)\.(gz|Z|bz2)$}s) {
48 my $suffix = "-$2";
49 my @preprocess = $3 eq "bz2" ? qw(bzip2 -d -c) : qw(gzip -d -c);
51 my ($fh, $tmpname) = tempfile(SUFFIX => $suffix,
52 DIR => File::Spec->tmpdir, UNLINK => 1)
53 or die "zrun: cannot create temporary file: $!\n";
55 if (my $child = fork) {
56 $child{$child} = $argument;
57 $argument = $tmpname;
59 elsif (defined $child) {
60 STDOUT->fdopen($fh, "w");
61 exec @preprocess, $argument;
63 else {
64 die "zrun: cannot fork to handle $argument: $!\n";
67 push @argument, $argument;
70 while (%child and (my $pid = wait) != -1) {
71 if (defined(my $argument = delete $child{$pid})) {
72 if ($? & 255) {
73 die "zrun: preprocessing for $argument terminated abnormally: $?\n";
75 elsif (my $code = $? >> 8) {
76 die "zrun: preprocessing for $argument terminated with code $code\n";
81 my $status = system $program ($program, @argument);
82 if ($status & 255) {
83 die "zrun: $program terminated abnormally: $?\n";
85 else {
86 my $code = $? >> 8;
87 exit $code;