Read variables from wp-config.php

I'm busy writing basic migration scripts for some WP sites, and I'm trying to automate the creation of the mysql database and user credentials from reading the wp-config file

how can I read the following variables from the wp-config file, so that I actually get 3 variables in a bash script:

/** The name of the database for WordPress */ define('DB_NAME', 'somedbname'); /** MySQL database username */ define('DB_USER', 'someusername'); /** MySQL database password */ define('DB_PASSWORD', 'somerandompassword'); 

For example, my result should effectively give me:

 WPDBNAME=somedbname WPDBUSER=somedbuser WPDBPASS=somerandompassword 
+8
variables scripting bash shell
source share
6 answers

Try the following:

 WPDBNAME=`cat wp-config.php | grep DB_NAME | cut -d \' -f 4` WPDBUSER=`cat wp-config.php | grep DB_USER | cut -d \' -f 4` WPDBPASS=`cat wp-config.php | grep DB_PASSWORD | cut -d \' -f 4` 
+21
source share

If you want to use wp-config data to connect to mysql, you can use;

 mysql -u `cat wp-config.php | grep DB_USER | cut -d \' -f 4` -p`cat wp-config.php | grep DB_PASSWORD | cut -d \' -f 4` -h `cat wp-config.php | grep DB_HOST | cut -d \' -f 4` `cat wp-config.php | grep DB_NAME | cut -d \' -f 4` 
+3
source share

you can use awk:

 awk -F"[()']" '/^define/{printf "%s=\"%s\"\n", $3, $5;}' < foo.php 

This will give you:

 DB_NAME="somedbname" DB_USER="someusername" DB_PASSWORD="somerandompassword" 

Note that this solution will work with variables containing spaces.

+2
source share
 find . -name "wp-config.php" -print0 | xargs -0 -r grep -e "DB_NAME" -e "DB_USER" -e "DB_PASSWORD" 
0
source share

Here is an example of a universal way to pass php variables to bash without the need for parsing:

 #!/bin/bash source <(php -r 'require("wp-config.php"); echo("DB_NAME=".DB_NAME."; DB_USER=".DB_USER."; DB_PASSWORD=".DB_PASSWORD); ') mysqldump --user $DB_USER --password="$DB_PASSWORD" $DB_NAME | gzip > $DB_NAME-$(date +%Y%m%d%H%M%S).sql.gz 

An explanation of the algorithm in a few words:

  • run your php
  • print variables as var = value
  • source conclusion
  • use variables in bash
0
source share

If you are trying to reset the MySQL database, you can also use the wp-cli db export function:

 wp db export --path=PATHTOYOURWP 
0
source share

All Articles