bash和php的设置文件


settings file for bash and php

我有一个涉及php和bash脚本的项目。

我想将所有用户设置外包到一个文件"settings.conf"中。因此,这个文件应该包含bash变量和php变量。

然而,bash会发现php代码非常令人恼火,而且php无法处理bash代码。

确保我的php脚本只处理文件的php部分,而bash只关心bash部分的最佳实践是什么?

设置文件可能看起来像这个

### Settings-File
## php-settings
<$php
    $language    = "en";
    $url         = "http://foo.bar";
    $copyright   = "Copyleft License";
?>
## end php-settings
## bash-settings
    pathToCertainFile="/home/johndo/files/certainFile"
## end bash-settings
## EOF

您不应该使用PHP和Bash本机解析的单个设置文件,而应该以对您的设置有意义的格式存储您的设置,并使用这两个脚本读取该文件。它不需要是可执行的。它只需要包含您的设置。

settings.conf:

foo="this"
bar="that"
someint=123

bash脚本可能如下所示:

#!/usr/local/bin/bash
eval `egrep '^[a-z]+=("[a-z0-9]+"|[0-9]+)$' settings.conf`
printf "foo=%s'nbar=%s'nsomeint=%s'n'n" "$foo" "$bar" "$someint"

请注意,使用eval通常是个坏主意。bash中还有其他(更好的)解决方案。我这样做是为了权宜之计。

PHP脚本可能如下所示:

#!/usr/local/bin/php
<?php
$fh=fopen("settings.conf", "r");
while ($line=fgets($fh, 80)) {
  if (preg_match('/^[a-z]+=("[a-z0-9]+"|[0-9]+)$/', $line)) {
    $line_a=explode("=", $line);
    $conf[$line_a[0]]=$line_a[1];
  }
}
print_r($conf);

这些例子确实有效:

ghoti@pc $ ./doit
foo=this
bar=that
someint=123
ghoti@pc $ ./doit.php 
Array
(
    [foo] => "this"
    [bar] => "that"
    [someint] => 123
)
ghoti@pc $ 

speendo,为什么要使用bash运行cron作业?只需将您的设置保存为PHP格式,并使用像上面ghoti的doit.php这样的PHP脚本。PHP是一种非常有效的shell和cron脚本语言。