deminy/

shellwrap

将任何命令行工具用作PHP函数。

0.4.1 2013-12-23 04:05 UTC

This package is auto-updated.

Last update: 2024-09-05 02:23:01 UTC


README

这是什么?

这是一个在PHP中使用强大的Linux/Unix工具的美丽方式。轻松且逻辑地将命令串联起来,捕获错误作为PHP异常,并使用简单而强大的语法。与任何命令行工具自动配合使用。

特性

  • 灵活且性感的语法。
  • 如果可执行程序返回错误,将抛出异常。
  • 二进制文件的路径将自动解析。
  • 所有参数都将正确转义。
  • 用于流式输出的回调函数。

示例

<?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'
));


?>

示例:跟踪文件并添加时间戳到输出

您可以将命令的输出流式传输到回调函数中。例如

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

确保文件 'log' 存在。这将输出时间戳和输入。尝试将内容输出到日志文件中。

转义码用于在终端中添加一些颜色。

交互式Shell

ShellWrap还提供交互式Shell模式。您可以通过输入以下内容来访问它

./bin/shellwrap

警告

不要使用任何用户输入的数据与这些命令。即使是非常偏执的过滤,您也无法了解您使用的每个命令的所有潜在风险。动用您的智慧。

致谢

受到Python项目sh by Andrew Moffat的启发