Rand Stats

Shell::Capture

github:ppentchev

NAME

Shell::Capture - capture a command's output and exit code

SYNOPSIS

    use Shell::Capture;

    my Shell::Capture $c .= capture('id', '-u', '-n');
    if $c.exitcode != 0 {
        die "Could not execute id -u -n\n";
    } elsif $c.lines.elems != 1 {
        die "id -u -n returned something unexpected:\n" ~ $c.lines.join("\n") ~ "\n";
    }
    say "Got my username: " ~ $c.lines[0];

    sub fail($r, @cmd) {
        die "fail with exit code $r.exitcode() and $r.lines().elems() " ~
            "line(s) of output and cmd " ~ @cmd;
    }

    $c .= capture-check(:accept(0, 3), 'sh', '-c', 'date');
    say "The current date is $c.lines()[0]" if $c.exitcode == 0;

    $c .= capture-check(:accept(0, 3), 'sh', '-c', 'date; exit 3');
    say "The current date is $c.lines()[0]" if $c.exitcode == 3;

    $c .= capture-check(:accept(0, 3), :&fail, 'sh', '-c', 'date; exit 1');
    say 'not reached, fail() dies';

    $c .= capture-check('git', 'ls-files', '-z', :nl("\0"));
    say 'Got some unquoted filenames from Git:';
    $c.lines>>.say;

    $c .= capture-check('env', 'LANG=fr_FR.ISO-8859-1', 'date', :enc('ISO-8859-1'));

DESCRIPTION

This class provides two methods to execute an external command, capture its output and exit code, and, in capture-check(), raise an error on unexpected exit code values.

FIELDS

METHODS

AUTHOR

Peter Pentchev <roam@ringlet.net>

COPYRIGHT

Copyright (C) 2016, 2017 Peter Pentchev

LICENSE

The Shell::Capture module is distributed under the terms of the Artistic License 2.0. For more details, see the full text of the license in the file LICENSE in the source distribution.