0

I am trying to retrieve some output from php, using bash. So far I have this:

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

All in all I am having trouble with the String interpolation. Right now I get:

line 10: <?php: command not found

So how can I properly escape the string such that the whole php code?

All in all, the PHP should generate output like that:

key=value
key2=value2

which can be "sourced" by the bash

Thanks in Ahead!

3 Answers 3

2

Using Here String

php <<< "$CODE"

Using Pipe

echo "$CODE" | php

If you want to store the output into a variable, use the command substitution:

result=$(php <<< "$CODE")
result=$(echo "$CODE" | php)
Sign up to request clarification or add additional context in comments.

1 Comment

This is the more complete answer, so I will choose that one!
2

This is wrong: RESULT=$($CODE | php) - shell variable can't be passed like that, it attempts to run $CODE as a command.

Instead you can do RESULT=$(echo "$CODE" | php) or RESULT=$(php <<<"$CODE")

Comments

0

I think you have 2 errors in here:

  1. error in your here-doc block. No need for ' around PHP.
  2. You need to escape the $ in your PHP code, or otherwise it will be expanded by bash.

Try:

#!/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

This will print out:

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

Which can be evaluated in php.

2 Comments

Having ' around PHP in the Heredoc statement is a good thing. It means that the content won't be subjected to expansion of special characters - therefore there will be no need to add backslashes before $.
Thanks for that info. I wasn't aware of that. One never stops learning.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.