开发者

read variables from wp-config.php

开发者 https://www.devze.com 2023-04-08 20:58 出处:网络
I\'m busy writing a basic migration scripts for some WP sites, and i\'m trying to automate creating mysql database and user credentials from reading the wp-config file

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

how c开发者_Python百科an i read the following variables from the wp-config file so that i effectively end up with 3 variables within 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');

eg my output should effectively give me:

WPDBNAME=somedbname
WPDBUSER=somedbuser
WPDBPASS=somerandompassword


Try this:

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`


If you want to use wp-config details 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`


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.


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


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

wp db export --path=PATHTOYOURWP


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

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

Algorithm explanation in a few words:

  1. run your php
  2. print variables as var=value
  3. source output
  4. use variables in bash
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号