parse credentials from PHP configuration file

I’d like to write bash script to parse data from a configuration file. I searched for this but without finding something I could modify to suit my needs.

Joomla! config file:

   public $access = '1';
   public $debug = '0';
   public $debug_lang = '0';
   public $dbtype = 'mysqli';
   public $host = 'localhost';
   public $user = 'template';
   public $password = 'template';
   public $db = 'template_druha';
   public $dbprefix = 'dsf1i_';
   public $live_site = '';
   public $secret = '2w9gHzPb4HfAs2Y9';
   public $gzip = '0';
   public $error_reporting = 'default';

I’d like to parse the database credentials on lines with "$user" and "$password" and store them in a variable. What is the best practice?

Answer

With GNU grep, you could do:

user=$(grep -oP "\$user.+?'K[^']+" file)
pass=$(grep -oP "\$password.+?'K[^']+" file)

The -P enables Perl Compatible Regular Expressions, which give us K (ignore anything matched so far). The -o means “only print the matching portion of the line. Then, we search for $var (we need three , to avoid expanding the variable and to avoid the $ being taken as part of the regex), a single quote and one or more non-' characters until the next '.

Alternatively, you could use awk:

user=$(awk -F"'" '/$user/{print $2}' file)
pass=$(awk -F"'" '/$password/{print $2}' file)

Here, we are setting the field delimiter to ', so the value of the variable will be the second field. The awk command prints the second field of matching lines.

Leave a Reply

Your email address will not be published. Required fields are marked *