PHPackages                             ptlis/shell-command - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [CLI &amp; Console](/categories/cli)
4. /
5. ptlis/shell-command

ActiveLibrary[CLI &amp; Console](/categories/cli)

ptlis/shell-command
===================

A basic wrapper around execution of shell commands.

1.3.0(5y ago)2256.0k↓25%42MITPHPPHP &gt;=7.2.0

Since Jan 20Pushed 3y ago1 watchersCompare

[ Source](https://github.com/ptlis/shell-command)[ Packagist](https://packagist.org/packages/ptlis/shell-command)[ RSS](/packages/ptlis-shell-command/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (2)Dependencies (4)Versions (41)Used By (2)

ptlis/shell-command
===================

[](#ptlisshell-command)

A developer-friendly wrapper around execution of shell commands.

There were several goals that inspired the creation of this package:

- Use the [command pattern](https://en.wikipedia.org/wiki/Command_pattern) to encapsulate the data required to execute a shell command, allowing the command to be passed around and executed later.
- Maintain a stateless object graph allowing (for example) the spawning of multiple running processes from a single command.
- Provide clean APIs for synchronous and asynchronous usage.
- Running processes can be wrapped in promises to allow for easy composition.

[![Build Status](https://camo.githubusercontent.com/4bbbf6016d54bd49b32d75b69dcdcc9dced155c965b48434acff65e571e03b5a/68747470733a2f2f6170692e7472617669732d63692e636f6d2f70746c69732f7368656c6c2d636f6d6d616e642e7376673f6272616e63683d6d6173746572)](https://app.travis-ci.com/github/ptlis/shell-command) [![codecov](https://camo.githubusercontent.com/ccb52dc4e26f02f6e2a6f34a81fd540361a11b2a3f84a3a8f35b308991513539/68747470733a2f2f636f6465636f762e696f2f67682f70746c69732f7368656c6c2d636f6d6d616e642f6272616e63682f6d61737465722f67726170682f62616467652e7376673f746f6b656e3d744a734c6236314c5632)](https://codecov.io/gh/ptlis/shell-command) [![Latest Stable Version](https://camo.githubusercontent.com/67e5f14f6404ba3141dfce0ccaf7380076da349cf9c64fba280b25737c3e223c/68747470733a2f2f706f7365722e707567782e6f72672f70746c69732f7368656c6c2d636f6d6d616e642f762f737461626c652e706e67)](https://packagist.org/packages/ptlis/shell-command)

- [Install](#install)
- [Usage](#usage)
    - [The Builder](#the-builder)
        - [Set Command](#set-command)
        - [Set Process Timeout](#set-process-timeout)
        - [Set Poll Timeout](#set-poll-timeout)
        - [Set Working Directory](#set-working-directory)
        - [Add Arguments](#add-arguments)
        - [Add Raw Arguments](#add-raw-arguments)
        - [Add Environment Variables](#add-environment-variables)
        - [Add Process Observers](#add-process-observers)
        - [Build the Command](#build-the-command)
    - [Synchronous Execution](#synchronous-execution)
    - [Asynchronous Execution](#asynchronous-execution)
        - [Command::runAsynchronous](#commandrunasynchronous)
    - [Process API](#process-api)
        - [Process::getPromise](#processgetpromise)
- [Mocking](#mocking)
- [Contributing](#contributing)
- [Known limitations](#known-limitations)

Install
-------

[](#install)

From the terminal:

```
$ composer require ptlis/shell-command
```

Usage
-----

[](#usage)

### The Builder

[](#the-builder)

The package ships with a command builder, providing a simple and safe method to build commands.

```
use ptlis\ShellCommand\CommandBuilder;

$builder = new CommandBuilder();
```

The builder will attempt to determine your environment when constructed, you can override this by specifying an environment as the first argument:

```
use ptlis\ShellCommand\CommandBuilder;
use ptlis\ShellCommand\UnixEnvironment;

$builder = new CommandBuilder(new UnixEnvironment());
```

**Note:** this builder is immutable - method calls must be chained and terminated with a call to `buildCommand` like so:

```
$command = $builder
    ->setCommand('foo')
    ->addArgument('--bar=baz')
    ->buildCommand()
```

#### Set Command

[](#set-command)

First we must provide the command to execute:

```
$builder->setCommand('git')             // Executable in $PATH

$builder->setCommand('./local/bin/git') // Relative to current working directory

$builder->setCommand('/usr/bin/git')    // Fully qualified path

$build->setCommand('~/.script.sh')      // Path relative to $HOME
```

If the command is not locatable a `RuntimeException` is thrown.

#### Set Process Timeout

[](#set-process-timeout)

The timeout (in microseconds) sets how long the library will wait on a process before termination. Defaults to -1 which never forces termination.

```
$builder
    ->setTimeout(30 * 1000 * 1000)          // Wait 30 seconds
```

If the process execution time exceeds this value a SIGTERM will be sent; if the process then doesn't terminate after a further 1 second wait then a SIGKILL is sent.

#### Set Poll Timeout

[](#set-poll-timeout)

Set how long to wait (in microseconds) between polling the status of processes. Defaults to 1,000,000 (1 second).

```
$builder
    ->setPollTimeout(30 * 1000 * 1000)          // Wait 30 seconds
```

#### Set Working Directory

[](#set-working-directory)

You can set the working directory for a command:

```
$builder
    ->setCwd('/path/to/working/directory/')
```

#### Add Arguments

[](#add-arguments)

Add arguments to invoke the command with (all arguments are escaped):

```
$builder
    ->addArgument('--foo=bar')
```

Conditionally add, depending on the result of an expression:

```
$builder
    ->addArgument('--foo=bar', $myVar === 5)
```

Add several arguments:

```
$builder
    ->addArguments([
        '--foo=bar',
        '-xzcf',
        'if=/dev/sda of=/dev/sdb'
    ])
```

Conditionally add, depending on the result of an expression:

```
$builder
    ->addArguments([
        '--foo=bar',
        '-xzcf',
        'if=/dev/sda of=/dev/sdb'
    ], $myVar === 5)
```

**Note:** Escaped and raw arguments are added to the command in the order they're added to the builder. This accommodates commands that are sensitive to the order of arguments.

#### Add Raw Arguments

[](#add-raw-arguments)

**WARNING**: Do not pass user-provided data to these methods! Malicious users could easily execute arbitrary shell commands.

Arguments can also be applied without escaping:

```
$builder
    ->addRawArgument("--foo='bar'")
```

Conditionally, depending on the result of an expression:

```
$builder
    ->addRawArgument('--foo=bar', $myVar === 5)
```

Add several raw arguments:

```
$builder
    ->addRawArguments([
        "--foo='bar'",
        '-xzcf',
    ])
```

Conditionally, depending on the result of an expression:

```
$builder
    ->addRawArguments([
        '--foo=bar',
        '-xzcf',
        'if=/dev/sda of=/dev/sdb'
    ], $myVar === 5)
```

**Note:** Escaped and raw arguments are added to the command in the order they're added to the builder. This accommodates commands that are sensitive to the order of arguments.

#### Add Environment Variables

[](#add-environment-variables)

Environment variables can be set when running a command:

```
$builder
    ->addEnvironmentVariable('TEST_VARIABLE', '123')
```

Conditionally, depending on the result of an expression:

```
$builder
    ->addEnvironmentVariable('TEST_VARIABLE', '123', $myVar === 5)
```

Add several environment variables:

```
$builder
    ->addEnvironmentVariables([
        'TEST_VARIABLE' => '123',
        'FOO' => 'bar'
    ])
```

Conditionally, depending on the result of an expression:

```
$builder
    ->addEnvironmentVariables([
        'TEST_VARIABLE' => '123',
        'FOO' => 'bar'
    ], $foo === 5)
```

#### Add Process Observers

[](#add-process-observers)

Observers can be attached to spawned processes. In this case we add a simple logger:

```
$builder
    ->addProcessObserver(
        new AllLogger(
            new DiskLogger(),
            LogLevel::DEBUG
        )
    )
```

#### Build the Command

[](#build-the-command)

One the builder has been configured, the command can be retrieved for execution:

```
$command = $builder
    // ...
    ->buildCommand();
```

### Synchronous Execution

[](#synchronous-execution)

To run a command synchronously use the `runSynchronous` method. This returns an object implementing `CommandResultInterface`, encoding the result of the command.

```
$result = $command
    ->runSynchronous();
```

When you need to re-run the same command multiple times you can simply invoke `runSynchronous` repeatedly; each call will run the command returning the result to your application.

The exit code &amp; output of the command are available as methods on this object:

```
$result->getExitCode();         // 0 for success, anything else conventionally indicates an error
$result->getStdOut();           // The contents of stdout (as a string)
$result->getStdOutLines();      // The contents of stdout (as an array of lines)
$result->getStdErr();           // The contents of stderr (as a string)
$result->getStdErrLines();      // The contents of stderr (as an array of lines)
$result->getExecutedCommand();  // Get the executed command as a string, including environment variables
$result->getWorkingDirectory(); // Get the directory the command was executed in
```

### Asynchronous Execution

[](#asynchronous-execution)

Commands can also be executed asynchronously, allowing your program to continue executing while waiting for the result.

#### Command::runAsynchronous

[](#commandrunasynchronous)

The `runAsynchronous` method returns an object implementing the `ProcessInterface` which provides methods to monitor the state of a process.

```
$process = $command->runAsynchronous();
```

As with the synchronouse API, when you need to re-run the same command multiple times you can simply invoke `runAsynchronous` repeatedly; each call will run the command returning the object representing the process to your application.

### Process API

[](#process-api)

`ProcessInterface` provides the methods required to monitor and manipulate the state and lifecycle of a process.

Check whether the process has completed:

```
if (!$process->isRunning()) {
    echo 'done' . PHP_EOL;
}
```

Force the process to stop:

```
$process->stop();
```

Wait for the process to stop (this blocks execution of your script, effectively making this synchronous):

```
$process->wait();
```

Get the process id (throws a `\RuntimeException` if the process has ended):

```
$process->getPid();
```

Read output from a stream:

```
$stdOut = $process->readStream(ProcessInterface::STDOUT);
```

Provide input (e.g. via STDIN):

```
$process->writeInput('Data to pass to the running process via STDIN');
```

Get the exit code (throws a `\RuntimeException` if the process is still running):

```
$exitCode = $process->getExitCode();
```

Send a signal (SIGTERM or SIGKILL) to the process:

```
$process->sendSignal(ProcessInterface::SIGTERM);
```

Get the string representation of the running command:

```
    $commandString = $process->getCommand();
```

#### Process::getPromise

[](#processgetpromise)

Monitoring of shell command execution can be wrapped in a [ReactPHP Promise](https://github.com/reactphp/promise). This gives us a flexible execution model, allowing chaining (with [Promise::then](https://github.com/reactphp/promise#promiseinterfacethen)) and aggregation using [Promise::all](https://github.com/reactphp/promise#all), [Promise::some](https://github.com/reactphp/promise#some), [Promise::race](https://github.com/reactphp/promise#race) and their friends.

Building promise to execute a command can be done by calling the `getPromise` method from a `Process` instance. This returns an instance of `\React\Promise\Promise`:

```
$eventLoop = \React\EventLoop\Factory::create();

$promise = $command->runAsynchonous()->getPromise($eventLoop);
```

The [ReactPHP EventLoop](https://github.com/reactphp/event-loop) component is used to periodically poll the running process to see if it has terminated yet; once it has the promise is either resolved or rejected depending on the exit code of the executed command.

The effect of this implementation is that once you've created your promises, chains and aggregates you must invoke `EventLoop::run`:

```
$eventLoop->run();
```

This will block further execution until the promises are resolved/rejected.

Mocking
-------

[](#mocking)

Mock implementations of the Command &amp; Builder interfaces are provided to aid testing.

By type hinting against the interfaces, rather than the concrete implementations, these mocks can be injected &amp; used to return pre-configured result objects.

Contributing
------------

[](#contributing)

You can contribute by submitting an Issue to the [issue tracker](https://github.com/ptlis/shell-command/issues), improving the documentation or submitting a pull request. For pull requests i'd prefer that the code style and test coverage is maintained, but I am happy to work through any minor issues that may arise so that the request can be merged.

Known limitations
-----------------

[](#known-limitations)

- Supports UNIX environments only.

###  Health Score

40

—

FairBetter than 88% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity39

Limited adoption so far

Community18

Small or concentrated contributor base

Maturity70

Established project with proven stability

 Bus Factor1

Top contributor holds 98.4% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~60 days

Recently: every ~153 days

Total

38

Last Release

1892d ago

Major Versions

0.17.3 → 1.0.02019-08-10

PHP version history (4 changes)v0.1.0PHP &gt;=5.3.0

v0.11.0PHP &gt;=5.5.0

0.17.0PHP ^7.1.0

1.3.0PHP &gt;=7.2.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/7ff8b14a43509e32a3892de4a8907b3b7764a6f7910454ae3f0f03e2541eea5c?d=identicon)[ptlis](/maintainers/ptlis)

---

Top Contributors

[![ptlis](https://avatars.githubusercontent.com/u/508422?v=4)](https://github.com/ptlis "ptlis (308 commits)")[![DBX12](https://avatars.githubusercontent.com/u/6484542?v=4)](https://github.com/DBX12 "DBX12 (3 commits)")[![particleflux](https://avatars.githubusercontent.com/u/3686454?v=4)](https://github.com/particleflux "particleflux (1 commits)")[![pixelbrackets](https://avatars.githubusercontent.com/u/1592995?v=4)](https://github.com/pixelbrackets "pixelbrackets (1 commits)")

---

Tags

commandexecexecutephpprocessshellshellprocessruncommandexecuteexec

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/ptlis-shell-command/health.svg)

```
[![Health](https://phpackages.com/badges/ptlis-shell-command/health.svg)](https://phpackages.com/packages/ptlis-shell-command)
```

###  Alternatives

[league/climate

PHP's best friend for the terminal. CLImate allows you to easily output colored text, special formats, and more.

1.9k14.0M273](/packages/league-climate)[mrrio/shellwrap

Use any command-line tool as a PHP function.

738198.8k2](/packages/mrrio-shellwrap)[titasgailius/terminal

Terminal is an Elegent wrapper around Symfony's Process component.

512340.9k11](/packages/titasgailius-terminal)[shapecode/cron-bundle

This bundle provides scheduled execution of Symfony commands

59493.0k2](/packages/shapecode-cron-bundle)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
