【问题标题】:Best/easiest way to parse configuration parameters in Sh/Bash and php在 Sh/Bash 和 php 中解析配置参数的最佳/最简单方法
【发布时间】:2011-03-29 15:42:36
【问题描述】:

我参与了每个 php 项目(大约 25 个!),一些 sh ​​脚本可以帮助我完成日常任务,例如部署、repo 同步、数据库导出/导出等。

我管理的所有项目的sh脚本都是一样的,所以必须有一个配置文件来存储依赖于项目的不同参数:

# example conf, the sintaxys only needs to be able to have comments and be easy to edit.
host=www.host.com
administrator_email=guill@company.com
password=xxx

我只需要找到一种可以从 sh 脚本中读取(解析)此配置文件的干净方法,同时能够从我的 PHP 脚本中读取相同的参数。无需使用 XML。

你知道一个好的解决方案吗?

吉列尔莫

【问题讨论】:

    标签: php linux bash configuration scripting


    【解决方案1】:

    【讨论】:

    • 是的,但是,有没有一种简单的方法可以从 Sh 脚本中读取 INI?
    【解决方案2】:

    只需将脚本 conf 文件作为另一个 sh 文件获取!。

    例子:

    conf-file.sh:

    # A comment
    host=www.host.com
    administrator_email=guill@company.com
    password=xxx
    

    您的实际脚本:

    #!/bin/sh
    
    . ./conf-file.sh
    
    echo $host $administrator_email $passwword
    

    同样的conf-file可以用PHP解析:http://php.net/manual/en/function.parse-ini-file.php

    【讨论】:

    • 谢谢伙计!您的解决方案听起来很简单,但我了解 INI 文件 cmets 以“;”开头而不是像 SH 中的“#”。对吗?
    • 并非如此,'#' 仍然可以使用,但是,如果您使用 >= v5.3,则会引发警告。任何较低的版本,都不会引发警告。 php.net/manual/en/function.parse-ini-file.php
    【解决方案3】:

    如果您不想像 pavanlimo 显示的那样获取文件,另一种选择是使用循环拉入变量:

    while read propline ; do 
       # ignore comment lines
       echo "$propline" | grep "^#" >/dev/null 2>&1 && continue
       # if not empty, set the property using declare
       [ ! -z "$propline" ] && declare $propline
    done < /path/to/config/file
    

    在 PHP 中,同样的基本概念适用:

    // it's been a long time, but this is probably close to what you need
    function isDeclaration($line) {
        return $line[0] != '#' && strpos($line, "=");
    }
    
    $filename = "/path/to/config/file";
    $handle = fopen($filename, "r");
    $contents = fread($handle, filesize($filename));
    $lines = explode("\n", $contents); // assuming unix style
    // since we're only interested in declarations, filter accordingly.
    $decls = array_filter($lines, "isDeclaration");
    // Now you can iterator over $decls exploding on "=" to see param/value
    fclose($handle);
    

    【讨论】:

    • 谢谢!听起来不错。但我猜它并没有轻松解决从 PHP 读取的可能性......
    • 已编辑以包含可能的 PHP 解决方案。
    • 感谢您的回答。我会考虑,但考虑上述解决方案更容易:-)
    【解决方案4】:

    从 sh/bash 解析 ini 文件

    #!/bin/bash
    #bash 4
    shopt -s extglob
    while IFS="=" read -r key value
    do
      case "$key" in
       !(#*) )
         echo "key: $key, value: $value"
         array["$key"]="$value"
         ;;
      esac
    done <"file"
    echo php -r myscript.php ${array["host"]}
    

    然后在 PHP 中,使用 argv

    【讨论】:

      【解决方案5】:

      对于 Bash INI 文件解析器,另请参阅:

      http://ajdiaz.wordpress.com/2008/02/09/bash-ini-parser/

      【讨论】:

        猜你喜欢
        • 2013-10-09
        • 2013-01-25
        • 1970-01-01
        • 2017-12-22
        • 1970-01-01
        • 1970-01-01
        • 2022-11-07
        • 2011-06-21
        • 2010-09-06
        相关资源
        最近更新 更多