NAME
    Sys::Cmd - Run a system command or spawn a process

VERSION
    v0.986.4 (2026-12-04)

SYNOPSIS
        use Sys::Cmd qw/run runsub spawn/;

        # One-shot
        my $output = run( 'ls', '--long' );
        my @XYZ = run( 'cat', '-n', { input => "X\nY\nZ\n", } );

        my ($out, $err, $exit);
        run( 'ls', 'FILE_NOT_FOUND', {
            out => \$out,
            err => \$err,
            exit => \$exit,
        });

        # Repeatable
        my $ls = runsub( 'ls',        # Returns a subref
            {
                dir => '/tmp',
                out => \$out,
            }
        );
        $ls->('--long')                 &&  print $out;
        $ls->({ dir => '/elsewhere'})   &&  print $out;

        # File-handles
        my $proc = spawn( @cmd );
        printf "pid %d\n", $proc->pid;

        while ( defined ( my $line = $proc->stdout->getline ) ) {
            $proc->stdin->print("thanks\n");
        }
        warn $proc->stderr->getlines;

        $proc->wait_child || warn $proc->status;

DESCRIPTION
    Sys::Cmd lets you run a system command and capture its output, or
    spawn and interact with a process through its "stdin", "stdout" and
    "stderr" handles. It offers a kind of templating for multiple calls
    to the same command with pre-defined defaults.

    Neither Perl's builtin external process functions or the plethora of
    modules on CPAN fit my desire for:

    *   Efficient process spawning

    *   Warn on error output

    *   Exception on failure

    *   Capture output, error and exit separately

    *   Sensible exit and signal values

    *   File handle access

    *   Automatic locale-aware handle encoding

    *   Template functions for repeated calls

    So this implementation aims for a small dependency footprint and
    predictable behaviour. Command lookup is via File::Which. Fast
    spawning is via Proc::FastSpawn. It deliberately does not (yet)
    manage "SIGCHLD", provide timeouts or process groups, or integrate
    with an event loop.

  Command Path
    All functions take a @cmd list that specifies the command and its
    arguments. The first element of @cmd determines what/how things are
    run:

    *   If it has one or more path components (absolute or relative) it
        is executed as is, with Proc::FastSpawn.

    *   If it is a CODE reference (subroutine) then a fork is performed
        before calling it in the child process. Unsupported on Win32.

    *   Everything else is looked up using File::Which and the result is
        executed with Proc::FastSpawn.

    The remaining scalar elements of @cmd are passed as arguments.

  Common Options
    A function's @cmd list may also include an optional "\%opts" HASH
    reference to adjust aspects of the execution. The following
    configuration items (key -> default) are common to all Sys::Cmd
    functions.

    dir -> $CWD
        The working directory the command will be run in. Note that a
        relative command path might not be valid if the current
        directory changes.

        The current process changes directory while the child is
        spawned, then the old directory is restored. Other threads and
        signal handlers in the parent can observe the temporary change.
        If it cannot be restored, spawn() and run() die.

    encoding -> $Encode::Locale::ENCODING_LOCALE
        A string value identifying the encoding that applies to
        input/output file-handles, command arguments, and environment
        variables. Defaults to the 'locale' alias from Encode::Locale.

    env -> {}
        A hashref containing key/values to be added to the current
        environment at run-time. If a key has an undefined value then
        the key is removed from the environment altogether.

        %ENV in the parent process is replaced with a modified copy
        while the child is spawned, then restored. Other threads and
        signal handlers in the parent can observe the temporary values.

    input -> undef
        A scalar (string), or ARRAY reference, which is fed to the
        command via its standard input, which is then closed. An empty
        value ('') or empty list will close the command's standard input
        without printing. An undefined value (the default) leaves the
        handle open.

        Some commands close their standard input on startup, which
        causes a SIGPIPE when trying to write to it, for which Sys::Cmd
        will warn.

FUNCTIONS
    The following are exportable from Sys::Cmd:

  One-Shot Functions
    run( @cmd, [\%opt] ) => $output | @output
        Executes @cmd and waits for the process to exit. Raises an
        exception in the event of non-zero exit value, otherwise warns
        for any errors received. In array context returns a list of
        lines instead of a scalar string. %opt accepts the following
        additional configuration keys:

        out -> \$scalar
            A reference to a scalar which is populated with output. When
            given run() returns nothing.

        err -> \$scalar
            A reference to a scalar which is populated with error
            output. When given run() does not warn of errors.

        exit -> \$scalar
            A reference to a scalar which is populated with the exit
            value. When given run() does not raise an exception on a
            non-zero exit.

    spawn( @cmd, [\%opt] ) -> Sys::Cmd::Process
        Return an object representing the process running according to
        @cmd and "\%opt". This is the core mechanism underlying "run".

        You can interact with the process object via its cmdline(),
        stdin(), stdout(), stderr(), close(), wait_child(), exit(),
        signal(), core() attributes and handles. See Sys::Cmd::Process
        for details.

  Template Functions
    When repeatedly calling a command, possibly with only slightly
    different arguments or environments, a kind of "templating"
    mechanism can be useful, to avoid repeating full configuration
    values and wearing a path lookup penalty each call.

    runsub( @cmd, [\%opt] ) -> CODEref
        Returns a subroutine reference representing a *future* command
        to be executed in the style of "run", with default arguments and
        options. When called, additional arguments and options are
        *merged*:

            use Sys::Cmd 'runsub';
            my $git = runsub(
                'git',
                {
                    env => {
                        GIT_AUTHOR_NAME  => 'Geekette',
                        GIT_AUTHOR_EMAIL => 'xyz@example.com',
                    }
                }
            );

            my @list   = $git->( 'add', 'file.txt' );
            my $result = $git->( 'commit', 'HEAD',
                {
                    env => {
                        GIT_AUTHOR_NAME  => 'Override',
                    }
                }
            ));

    spawnsub( @cmd, [\%opt] ) -> CODEref
        Returns a subroutine reference representing a *future* process
        to be created in the style of "spawn", with default arguments
        and options. When called, additional arguments and options are
        *merged*.

            use Sys::Cmd 'spawnsub';
            my $cmd = spawnsub('command');
            my @kids;
            foreach my $i ( 0 .. 9 ) {
                $kids[$i] = $cmd->( 'arg', $i );
                $kids[$i]->stdin->print("Hello\n");
            }
            print $_->pid . ': ' . $_->stdout->getlines for @kids;
            $_->wait_child for @kids;

ALTERNATIVES
  Lower-level primitives
    Perl builtins ("system", "qx//", "fork"+"exec", piped "open")
        Enough for one-off commands. No separate stderr capture or
        default error policy.

    IPC::Open3
        Low-level stdin/stdout/stderr handles. You have to do your own
        exit handling.

    Proc::FastSpawn, Proc::Fork, IPC::Exe
        Spawning primitives. Sys::Cmd builds on Proc::FastSpawn rather
        than competing with it.

  Similar scope
    System::Command
        Closest match to Sys::Cmd as it is the ancestor after all.
        Similar process object and "cwd"/"env"/"input" options, but uses
        fork+exec internally and the multi-thousand-line IPC::Run on
        Windows.

        It does process groups and tracing, and keeps reaping safe when
        handles outlive the object. Has no one-shot output collection or
        template feature.

  One-shot capture
    IPC::Run3, IPC::Cmd
        Capture stdin/stdout/stderr for a command that runs to
        completion. IPC::Run3 spools through files to avoid blocking; it
        leaves $? to the caller. No interactive process handles.

    Capture::Tiny
        Captures stdout/stderr around an arbitrary Perl block, including
        XS and child processes. Not a process manager: no input, no
        interactive handles.

    IPC::System::Simple
        A safer "system"/backticks replacement with good diagnostics. No
        interactive handles and no separate stderr capture in capture().

  Richer process control
    IPC::Run
        Pumping, timeouts, pseudo-terminals and pipelines. Much larger
        API and dependency surface.

  Different scope
    Event-loop modules
        AnyEvent::Run, AnyEvent::Util, POE::Pipe::TwoWay and other
        event-loop process helpers integrate spawning with an event
        loop. Sys::Cmd is blocking.

    Supervision and background processes
        Child, Proc::Background and Forks::Super manage process
        lifecycles, pools or background jobs rather than direct command
        I/O.

    Narrower helpers
        Argv, Command::Run, IO::Pipe, IPC::Capture,
        IPC::Command::Multiplex, IPC::Open3::Simple,
        IPC::RunSession::Simple, IPC::ShellCmd and Spawn::Safe cover
        specific corners of the same space.

SUPPORT
    This distribution is managed via github:

        https://github.com/mlawren/p5-Sys-Cmd

    This distribution follows the semantic versioning model:

        http://semver.org/

    Code is tidied up on Git commit using githook-perltidy:

        http://github.com/mlawren/githook-perltidy

AUTHOR
    Mark Lawrence <mark@rekudos.net>, based heavily on
    Git::Repository::Command by Philippe Bruhat (BooK).

COPYRIGHT AND LICENSE
    Copyright 2011-2026 Mark Lawrence <mark@rekudos.net>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.

