在CLI模式下从PHP运行交互式shell命令

时间:2016-03-01 21:35:46

标签: php bash shell interactive

我有一个PHP CLI脚本,想要从该脚本执行交互式bash命令(例如less huge-file.txt)并获得相同的视图(使用less,例如导航控件),就好像我已经开始它直接来自终端。

正常system()调用是不够的,因为它们不会暂停并且只是立即返回所有输出(例如less)。

感觉是我有一个CLI脚本来组织几个任务。其中一些使用复杂的bash命令,我只想从PHP调用bash脚本,但获得原始的终端行为。

2 个答案:

答案 0 :(得分:0)

是的,这是可能的。我最近发布了一个项目,允许PHP获取真正的Bash shell并与之交互。在此处获取:https://github.com/merlinthemagic/MTS

我怀疑你是不是真的想用更少的脚本(这会变得难看,head / tail / sed / awk是你在文本操作中的朋友),但是获得真正的shell行为是非常可能的。

下载后,您只需使用以下代码:

$shell    = \MTS\Factories::getDevices()->getLocalHost()->getShell('bash', false);

//open file in less. $return1 will contain the view and the first part of the file you opened. The second argument is needed to delimit the return since less will not end in a shell prompt.
$return1  = $shell->exeCmd('less /path/to/huge-file.txt', 'huge-file.txt');

//quit less, you must do this or the shell will hang on the less prompt and will have to be forcefully terminated.
$return2  = $shell->exeCmd('q');

答案 1 :(得分:-1)

scanf()

这会调用命令并传递所有控件等,以便与普通proc_open( 'less huge-file.txt', array( STDIN, STDOUT, STDERR), $pipes); 无区别。

与我能找到的其他例子相比,仍然有点笨重,但要短得多。