我有一个通过CLI运行的PHP脚本。 反过来,我希望该脚本调用 bash 脚本,但最好是我想分解 BASH 请求,以便我可以看到正在发生的操作。
我似乎可以设置环境变量,它们似乎存在于 shell_exec() 函数之间。 但即使我有一个源文件,例如:
来源 ./bashes/functions.sh
在源文件中,我使用"export -f function-name"在执行下一行之前导出脚本中的函数,下一行看不到函数。
$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));
}
函数 $output->writeln 是一个帮助程序函数,仅用于回显返回的结果。 但基本上我得到的错误是
sh: now: command not found
now 定义为包含的 bash_testing.sh shell 脚本中的函数。
有人知道我如何解决这个问题吗?
以下是 ./bashes/functions.sh 文件的源代码:
function now {
date -u +%T
}
export -fx now
有一种方法可以维护单个 bash shell,执行命令并处理返回。我最近发布了一个项目,允许PHP获取并与真正的Bash shell进行交互。在这里获取:https://github.com/merlinthemagic/MTS
我建议不要触发 bash 脚本,而是触发 induvidual 命令。这样您就可以处理返回,而不必在 bash 中构建异常处理。
下载后,您只需使用以下代码:
//get a real bash shell.
$shell = MTSFactories::getDevices()->getLocalHost()->getShell('bash', false);
$return1 = $shell->exeCmd($command1);
//logic to handle the return
$return2 = $shell->exeCmd($command2);
//logic to handle the return
.....等