BASH-从PHP获得结果

时间:2016-11-07 11:40:43

标签: php bash string-interpolation

我正在尝试使用bash从php检索一些输出。到目前为止,我有这个:

CODE="<?php chdir('$WWW');" # $WWW should be interpolated

CODE+=$(cat <<'PHP' # no interpolation for the rest of the code
    require_once('./settings.php'); 

    $db = $databases['default']['default'];

    $out = [
        'user=' . $db['username']
        //more here
    ];

    echo implode("\n", $out)
PHP)

echo $CODE    

#RESULT=$($CODE | php)

#. $RESULT

总而言之,我在使用字符串插值时遇到了麻烦。现在我得到:

line 10: <?php: command not found

那么我怎样才能正确地转义字符串以便整个php代码?

总而言之,PHP应该生成如下输出:

key=value
key2=value2

可以由bash“来源”

向前谢谢!

3 个答案:

答案 0 :(得分:2)

这是错误的:RESULT=$($CODE | php) - shell变量无法像这样传递,它会尝试将$CODE作为命令运行。

相反,您可以执行RESULT=$(echo "$CODE" | php)RESULT=$(php <<<"$CODE")

答案 1 :(得分:2)

使用Here String

<script src="http://www.google.com/jsapi" type="text/javascript"></script>

<script type="text/javascript">
    google.load('search', '1');

    google.setOnLoadCallback(function(){
        google.search.CustomSearchControl.attachAutoCompletion(
            'your-google-search-id',
            document.getElementById('search-field'),
            'search-form');
    });
</script>

<!-- example search form -->
<form id="search-form" action="/search">
    <input id="search-field" name="search-field" type="text" />  
    <input type="submit" value="Search" />
</form>

使用管道

     private void CheckMembers()
     {
        try
        {
            string query = "Select id, id-no, status From Members Where Head=@Head";

            sqlCommand = new SqlCommand(query, sqlConnection);
            sqlConnection.Open();
            sqlCommand.Parameters.AddWithValue("@Head", "2288885858");
            sqlDataReader = sqlCommand.ExecuteReader();

            if (sqlDataReader.HasRows)
            {
                fmGview.Visible = true;
                DataTable dt = new DataTable();
                dt.Load(sqlDataReader);
                MessageBox.Show(dt.ToString());
                fmGview.DataSource = dt;
            }
        }
        catch (Exception exp)
        {
            MessageBox.Show(exp.ToString(), "Exception in CheckMembers");
        }
        finally
        {
            CheckConnectionStatus();
        }
   }

如果要将输出存储到变量中,请使用command substitution

php <<< "$CODE"

答案 2 :(得分:0)

我认为你在这里有2个错误:

    你的here-doc块中的
  1. 错误。 PHP周围不需要'
  2. 您需要在PHP代码中转义$,否则它将被bash扩展。
  3. 尝试:

    #!/bin/bash
    
    CODE="<?php chdir('$WWW');" # $WWW should be interpolated
    
    CODE+=$(cat << PHP # no interpolation for the rest of the code
        //require_once('./settings.php'); 
    
        \$db = "foo";
    
        \$out = [
            'user=' . \$db
            //more here
        ];
    
        echo implode("\n", \$out)
    PHP
    )
    
    echo $CODE
    

    这将打印出来:

    <?php chdir("/tmp"); //require_once('./settings.php'); $db = "foo"; $out = [ 'user=' . $db //more here ]; echo implode("\n", $out);
    

    可以在php中评估。