How do I export variables from a PHP script in Bash?

I'm writing a Bash script to read database names from config.php files of each website, and then import the database from the backup repository. I tried to use source config.php but it seems it doesn't recognize PHP variables.

Any help would be appreciated.

  • 2
    can you give us examples of the php files you are wanting to read from? – gogoud Nov 24 '15 at 21:33
  • 1
    Naturally "source config.php" gave you errors: it's a different language than bash. You would get similar errors with "source config.pl" or "source config.c" etc – glenn jackman Nov 24 '15 at 21:38
  • It may be easiest to write PHP code to extract those variables in a format easily consumed from bash, but we will know once you post an example of what you want to read from. – dhag Nov 24 '15 at 21:41

A very simplified version would be something as follows:

2 lines in config.php:

cat config.php
$variable1 = 'foo with bar';
$variable1 = 'foo2 with bar2';

Set Bash $variable1 to last matching instance of $variable1 in config.php, just in case it has been reset. If you want to change it to the first match, simply change tail -1 to head -1 in the following code:

variable1="$(grep -oE '\$variable1 = .*;' config.php | tail -1 | sed 's/$variable1 = //g;s/;//g')"

Confirm Bash variable via echo:

echo "$variable1"
'foo2 with bar2'

Note that this will mostly work for strings. There are many types of PHP variables that cannot be directly converted to Bash variables. The code above will grab the last $variable1 referenced in config.php. Like I said, if that variable has been set multiple times, you can set to the first value or last value by toggling head or tail in the Bash command that sets the variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.