Keep bash shell functions between shell_exec(&

2019-08-11 16:32发布

问题:

I have a PHP script that is run via CLI. In turn I want that script to call a bash script, but preferably I would like to break up the BASH requests so I can see the action as it is happening.

I can seem to set Environmental variables and they seem to exist between shell_exec() functions. But even when I have a source file like:

source ./bashes/functions.sh

And in the source file I use "export -f function-name" to export the functions in the script before executing the next line, the next line does not see the functions.

  $file = file('./bashes/bash_testing.sh',FILE_SKIP_EMPTY_LINES);

  //we want to watch this in realtime so write each line seperately to shell.
  foreach($file as $command) {
    $output->writeln(shell_exec($command));
  }

The function $output->writeln is a helper function just to echo the returned result. But basically the error I get is

sh: now: command not found

now is defined as a function in the included bash_testing.sh shell script.

Anyone know how I can resolve this issue?

Here is the source to the ./bashes/functions.sh file:

function now {
  date -u +%T
}

export -fx now

回答1:

There is a way to maintain a single bash shell, execute commands and handle the return. 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 would suggest not triggering a bash script but rather trigger the induvidual commands. That way you can handle the return and not have to build exception handling in bash.

After downloading you would simply use the following code:

//get a real bash shell.
$shell    = \MTS\Factories::getDevices()->getLocalHost()->getShell('bash', false);

$return1  = $shell->exeCmd($command1);
//logic to handle the return

$return2  = $shell->exeCmd($command2);
//logic to handle the return

..... etc



标签: php bash shell