在多线程之前,在长时间运行的后台shell脚本中传递数组


Passing array in long running background shell script prior to multithreading

在crontab中,我添加了一个php脚本名称,从CLI SAPI模式运行此脚本,因此没有max_execution_time问题。

我可以使用空格传递几个参数。

system('/path/of/your/script.php param1 param2 > scriptlog.txt &')

但我需要传递一个数组,因为参数是shell脚本,并分解数组。

例如

system('/path/of/your/script.php array > scriptlog.txt &')

当您在应用程序中投射system时,您必须implode您的参数
只需像一样依次传递参数

system('/path/of/your/script.php param[0] param[1] > scriptlog.txt &')

这看起来像

system('/path/of/your/script.php '.implode(" ",$params).' > scriptlog.txt &')

如果你有报价,你可以看看escapestellarg

system('/path/of/your/script.php '.implode(" ",array_map("escapeshellarg",$params)).' > scriptlog.txt &')

然后在您的script.php中,用捕获参数

$args = $argv;
array_shift($args); //Because $args[0] is 'script.php'

如果您在script.php中捕获> scriptlog.txt &,请使用以下内容:

$args = $argv;
if (false !== ($pos = array_search(">",$args))) {
    $args = array_slice($args,1,$pos-1);
} else {
    array_shift($args);
}

请注意,只有当数组是非关联的时,这才有效
您需要编写另一个函数来检索关联参数

不能直接传递数组。理想情况下,您要做的是将数组的每个成员作为一个单独的参数传递出去,然后将它们读回以在脚本中使用。您还可以将要读取的参数数传递给脚本。即

$out = sizeof($array);
foreach ($array as $arg){
    $out = $out . ' ' . $arg;
}

这应该会给你的输出对象一个类似"4 param1 param2 param3 param4"的列表

然后,您只需要在bash脚本中使用ARGV来读取这些变量。

或者,您也可以使用字段分隔的列表,将其作为一个参数读取,然后使用字段分隔符上的拆分来拆分每个数组元素。