I got in every php project (around 25!), some sh scripts that help me with routine tasks such as deployment, repo syncronizing, databases exporting/export, etc.
The sh scripts are the same for all the projects I manage, so there must be a configuration file to store diferent parameters that depend on the project:
# 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
I just need to find a clean way in which this configuration file can be read (parsed) from a sh script, and at the same time, be able to read those same parameters from my PHP scripts. Without having to use XML.
Do you know a good solution for this?
Guillermo
If you don't want to source the file as pavanlimo showed, another option is to pull in the variables using a loop:
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
In PHP, the same basic concepts apply:
// 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);
Simply source the script conf file as another sh file!.
Example:
conf-file.sh:
# A comment
host=www.host.com
administrator_email=guill@company.com
password=xxx
Your actual script:
#!/bin/sh
. ./conf-file.sh
echo $host $administrator_email $passwword
And the same conf-file can be parsed in PHP: http://php.net/manual/en/function.parse-ini-file.php
For a Bash INI file parser also see:
http://ajdiaz.wordpress.com/2008/02/09/bash-ini-parser/
to parse the ini file from sh/bash
#!/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"]}
then from PHP, use argv
INI! http://php.net/manual/en/function.parse-ini-file.php