简体   繁体   中英

Run an interactive shell command from PHP in CLI mode

I have a PHP CLI script and want to execute an interactive bash command (eg less huge-file.txt ) from that script and get the same view (with less eg the navigation controls) as if I had started it directly from the terminal.

The normal system() call is not enough because they don't pause and just return all the output at once (in the case of eg less ).

Sense is that I have a CLI script that organises several tasks. Some of them use complex bash commands and I just want to invoke the bash scripts from PHP but get the original terminal behaviour.

proc_open( 'less huge-file.txt', array( STDIN, STDOUT, STDERR), $pipes);

This calls the command and passes all controls etc. through, so that there is no distinction to a normal less huge-file.txt .

Still a bit clunky but a lot shorter compared to other examples I could find.

Yes it is possible. I recently published a project that allows PHP to obtain and interact with a real Bash shell. Get it here: https://github.com/merlinthemagic/MTS

I doubt you are really looking to script using less (that will get ugly, head / tail / sed /awk are your friends in text manipulation), but getting a real shell behavior is very possible.

After downloading you would simply use the following code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM