I`m trying to execute a bash script using PHP, but the problem is that the script needs to have some commands and informations inputed during the execution process.
This is what I`m using
$old_path = getcwd(); chdir('/my/path/'); $output = shell_exec('./script.sh'); chdir($old_path);
The script execute OK, but I`m not able to input any option on the script.
Advertisement
Answer
shell_exec() and exec() are not able to run interactive scripts. For that you need a real shell. Here is a project that gives you a real Bash Shell: https://github.com/merlinthemagic/MTS
//if the script requires root access, change the second argument to "true". $shell = MTSFactories::getDevices()->getLocalHost()->getShell('bash', false); //What string do you expect to show in the terminal just before the first input? Lets say your script simply deletes a file (/tmp/aFile.txt) using "rm". In that case the example would look like this: //this command will trigger your script and return once the shell displays "rm: remove regular file" $shell->exeCmd("/my/path/script.sh", "rm: remove regular file"); //to delete we have to press "y", because the delete command returns to the shell prompt after pressing "y", there is no need for a delimiter. $shell->exeCmd("y"); //done
I am sure the return of the script is far more complex, but the example above gives you a model for how to interact with the shell.
I would also mention that you might consider not using a bash script to perform a sequence of events, rather issue the commands one by one using the exeCmd() method. That way you can handle the return and keep all error logic in PHP rather than splitting it up between PHP and BASH.
Read the documentation, it will help you.