Lovely PHP wrapper for using the command-line

Last update: May 3, 2022

ShellWrap

What is it?

It's a beautiful way to use powerful Linux/Unix tools in PHP. Easily and logically pipe commands together, capture errors as PHP Exceptions and use a simple yet powerful syntax. Works with any command line tool automagically.

Features

  • Flexible and sexy syntax.
  • Exceptions are thrown if the executable returns an error.
  • Paths to binaries are automatically resolved.
  • All arguments are properly escaped.
  • Callback functions for streaming output.

Examples

<?php 
require_once 'vendor/autoload.php';
use MrRio\ShellWrap as sh;

// List all files in current dir
echo sh::ls();

// Checkout a branch in git
sh::git('checkout', 'master');

// You can also pipe the output of one command, into another
// This downloads example.com through cURL, follows location, then pipes through grep to 
// filter for 'html'
echo sh::grep('html', sh::curl('http://example.com', array(
	'location' => true
)));

// Touch a file to create it
sh::touch('file.html');

// Remove file
sh::rm('file.html');

// Remove file again (this fails, and throws an exception because the file doesn't exist)

try {
	sh::rm('file.html');
} catch (ShellWrapException $e) {
	echo 'Caught failing sh::rm() call';
}


// This throws an exception, as 'invalidoption' is not a valid argument
try {
	echo sh::ls(array('invalidoption' => true));
} catch (ShellWrapException $e) {
	echo 'Caught failing sh::ls() call';
}

// Commands can be written multiple ways
sh::git('reset', array('hard' => true), 'HEAD');
sh::git('reset', '--hard', 'HEAD');
sh::git(array('reset', '--hard', 'HEAD'));

// Arguments passed in are automatically escaped, this expands to
// date --date '2012-10-10 10:00:00'
echo sh::date(array(
	'date' => '2012-10-10 10:00:00'
));

// If arg keys are one letter, is assumes one dash prefixing it
// date -d '2012-10-10 10:00:00'
echo sh::date(array(
	'd' => '2012-10-10 10:00:00'
));


?>

Example: Tailing a file and adding timestamps to output

You can stream the output of a command into a callback function. For example:

sh::tail('-f log', function($in) {
	echo "\033[32m" . date('Y-m-d H:i:s') . "\033[39m " . $in;
});

Make sure the file 'log' exists. This will output a timestamp, and the input. Try echoing into the log file.

The escape codes are to add a little colour to the terminal.

Interactive Shell

ShellWrap also ships with an interactive shell mode. You can access this by typing:

./bin/shellwrap

Warning

Don't use any user inputted data with these commands. Even with very paranoid filtering, you can't know all the potential pitfalls of each command you're using. Use your noggin.

Acknowledgements

Inspired by the Python project sh by Andrew Moffat

GitHub

https://github.com/MrRio/shellwrap
Comments
  • 1. Original namespace

    I'm using this wrapper for myself. I've created a composer package installable from packagist.org. I've created this branch to keep your namespace and contribute my changes. If you want them. Here is what I did:

    • added .gitignore
    • made it psr-0 compatible
    • ready to add to packagist.org
    • passed through php-cs-fixer (minor fixes, indentation, etc)
    • moved ShellWrap.php to src/MrRio for autoloading
    • moved examples to new directory
    • added LC_ALL=en_US to testDate() to avoid error in non-english environment

    NOTE: The diff on ShellWrap is the complete file due to directory changes..

    Reviewed by guumaster at 2013-04-06 21:24
  • 2. specify current working directory explicitly when executing shell commands

    If you use function chdir() to change working directory to a different directory first, following two statements should still return same directories. However, in Travis CI they return different directories back (the 2nd one returns the directory where the PHP script was invoked).

    1. getcwd()
    2. (string) ShellWrap::pwd()

    Thus we need to have the 4th parameter (getcwd()) specified explicitly here, also ideally it's unnecessary.

    Reviewed by deminy at 2018-06-15 23:50
  • 3. Magic method __toString() must return a string

    In some PHP IDE (e.g., PhpStorm) you may see that method _\MrRio\ShellWrap::_toString() is highlighted with notification saying

    __toString() method must return a string

    This could be triggered with following code piece where no actual shell command invoked:

    <?php
    require_once __DIR__ . '/vendor/autoload.php';
    
    echo (new MrRio\ShellWrap());
    ?>
    

    Although in reality people may not make method calls like that, it's better to get it fix to make variables consistent. Property \MrRio\ShellWrap::$output should be initialized and used as a string but not an array, as in the fix.

    Reviewed by deminy at 2018-03-29 23:08
  • 4. Composer >1.3.0 compatibility

    I've opened an issue against Boris here, however, I am also going open an issue here for anyone else experiencing this. When using shell wrap with a composer version >1.3.0, PHP gets reloaded to disable XDebug and causes an error to be thrown in the terminal. E.g.,

    PHP Warning:  Module 'pcntl' already loaded in Unknown on line 0
    
    Warning: Module 'pcntl' already loaded in Unknown on line 0
    

    As Boris is only used for the interactive debugger, is there any chance of a workaround? Boris hasn't had any commits or changes in years, maybe Psysh would be a good drop-in replacement?

    Reviewed by barchard at 2017-08-06 00:56
  • 5. Skip saving output to variable when using callback function

    My case is currently that I'm streaming use log files using sh::cat() and using a callback closure to pass the data (after a filter) to an PHPExcel object. The log files can easily get over 500MB. Looking through the code it seems that even when using a callback/closure, the output of the cat command still gets saved to a variable, making memory usage go up and up.

    I cannot grep on the log files as it's filled with IDs, possible conflicting with other data in the same line.

    Is this currently possible in a less memory consuming way? Else I'm also willing to submit a PR with some extra functionality on this. Reasoning could be that when streaming through a closure, no need is left to save things to the self::$output variable.

    Reviewed by stefandoorn at 2015-10-06 12:20
  • 6. Alternative piping syntax

    echo sh::grep('html', sh::curl('http://example.com', array(
        'location' => true
    )));
    

    In current API I don't like 2 things:

    1. inverted order of commands (grep -> curl) when actually curl | grep is intended
    2. "wrap" or functional style a(b(c()))

    It would be nice to have fluid API like this

    sh::curl('http://example.com')->pipe('grep', 'html')->pipe('whatever');
    

    or

    sh::curl('http://example.com')->sh('grep', 'html')->sh('whatever');
    

    or

    sh::curl('http://example.com')->grep('html')->whatever();
    

    @MrRio what do you think?

    Reviewed by Mihailoff at 2014-10-29 00:49
PHP Interminal is a command-line tool that gives you access to PHP Internals discussions in your terminal.
PHP Interminal is a command-line tool that gives you access to PHP Internals discussions in your terminal.

PHP Interminal is a command-line tool that gives you access to PHP Internals discussions in your terminal. ??

Dec 12, 2021
A PHP library for command-line argument processing

GetOpt.PHP GetOpt.PHP is a library for command-line argument processing. It supports PHP version 5.4 and above. Releases For an overview of the releas

May 24, 2022
Patrol is an elegant command-line tool that keeps your PHP Project's dependencies in check.
Patrol is an elegant command-line tool that keeps your PHP Project's dependencies in check.

Patrol is an elegant command-line tool that keeps your PHP Project's dependencies in check. Installation / Usage Requires PHP 8.0+ First, install Patr

May 6, 2022
Twitter raffles in the command line, with PHP and minicli
Twitter raffles in the command line, with PHP and minicli

Rafflebird Rafflebird is a highly experimental CLI application for giveaways / raffles on Twitter, built in PHP with Minicli. Disclaimer: The recent s

May 14, 2022
A PHP command line tool used to install shlink
A PHP command line tool used to install shlink

Shlink installer A PHP command line tool used to install shlink. Installation Install this tool using composer.

Jan 10, 2022
Command-line control panel for Nginx Server to manage WordPress sites running on Nginx, PHP, MySQL, and Let's Encrypt
Command-line control panel for Nginx Server to manage WordPress sites running on Nginx, PHP, MySQL, and Let's Encrypt

EasyEngine v4 EasyEngine makes it greatly easy to manage nginx, a fast web-server software that consumes little memory when handling increasing volume

May 22, 2022
Generic PHP command line flags parse library
Generic PHP command line flags parse library

PHP Flag Generic PHP command line flags parse library Features Generic CLI options and arguments parser. Support set value data type(int,string,bool,a

Mar 2, 2022
A simple command-line tool whose aim is to facilitate the continous delivery of PHP apps
A simple command-line tool whose aim is to facilitate the continous delivery of PHP apps

Deployer Simple command-line tool that aims to facilitate the continous delivery of PHP apps, particularly Laravel apps. Imagine you want to update yo

Sep 8, 2021
🍃 In short, it's like Tailwind CSS, but for the PHP command-line applications.
🍃 In short, it's like Tailwind CSS, but for the PHP command-line applications.

Termwind Termwind allows you to build unique and beautiful PHP command-line applications, using the Tailwind CSS API. In short, it's like Tailwind CSS

May 27, 2022
A PHP Command Line tool that makes it easy to compile, concat, and minify front-end Javascript and CSS/SCSS dependencies.

Front End Compiler A PHP Command Line tool that makes it easy to compile, concat, and minify front-end Javascript and CSS/SCSS dependencies. The minif

Nov 12, 2021
php command line script to DCA crypto from Coinbase Pro

dca.php A simple php script designed to be run via the command line via a cron job. This will connect to coinbase pro and buy the crypto coins specifi

Oct 22, 2021
A PHP library for command-line argument processing

GetOpt.PHP GetOpt.PHP is a library for command-line argument processing. It supports PHP version 7.1 and above. Releases For an overview of the releas

May 20, 2022
BetterWPCLI - a small, zero-dependencies, PHP library that helps you build enterprise WordPress command-line applications.
BetterWPCLI - a small, zero-dependencies, PHP library that helps you build enterprise WordPress command-line applications.

BetterWPCLI - a small, zero-dependencies, PHP library that helps you build enterprise WordPress command-line applications.

May 3, 2022
Command-Line Interface tools

Aura.Cli Provides the equivalent of request ( Context ) and response ( Stdio ) objects for the command line interface, including Getopt support, and a

May 6, 2022
Another Command Line Argument Parser

Optparse — Another Command Line Argument Parser Install 1. Get composer. 2. Put this into your local composer.json: { "require": { "chh/optparse

Nov 1, 2019
👨🏻‍🚀 A command-line tool that gives you the Alpine Day 2021 schedule in your timezone. 🚀
👨🏻‍🚀 A command-line tool that gives you the Alpine Day 2021 schedule in your timezone. 🚀

Alpine Day Schedule a command-line tool that gives you the Alpine Day 2021 schedule in your timezone. ?? Quick start Requires PHP 7.4+ # First, instal

Jun 10, 2021
A command line code generator for Drupal.

Drupal Code Generator A command line code generator for Drupal. Installation Download the latest stable release of the code generator.

May 20, 2022
Laracon Schedule a command-line tool that gives you the Laracon Online schedule in your timezone.
Laracon Schedule a command-line tool that gives you the Laracon Online schedule in your timezone.

Laracon Schedule a command-line tool that gives you the Laracon Online schedule in your timezone. ?? Quick start Requires PHP 7.4+ # First, install: c

Dec 13, 2021
Simple command-line tool to access HiWeb account information

Simple command-line tool to access HiWeb account information.

Nov 17, 2021