Bash 从wp-config.php读取变量

Bash 从wp-config.php读取变量,bash,shell,variables,scripting,Bash,Shell,Variables,Scripting,我正忙着为一些WP站点编写一个基本的迁移脚本,并试图通过读取WP配置文件来自动创建mysql数据库和用户凭据 如何从wp config文件中读取以下变量,以便在bash脚本中有效地得到3个变量: /** The name of the database for WordPress */ define('DB_NAME', 'somedbname'); /** MySQL database username */ define('DB_USER', 'someusername'); /** M

我正忙着为一些WP站点编写一个基本的迁移脚本,并试图通过读取WP配置文件来自动创建mysql数据库和用户凭据

如何从wp config文件中读取以下变量,以便在bash脚本中有效地得到3个变量:

/** 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');
例如,我的输出应该有效地为我提供:

WPDBNAME=somedbname
WPDBUSER=somedbuser
WPDBPASS=somerandompassword
试试这个:

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`
您可以使用awk:

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

请注意,此解决方案将使用包含空格的变量。

如果要使用wp config details连接到mysql,可以使用

find . -name "wp-config.php" -print0 | xargs -0 -r grep -e "DB_NAME" -e "DB_USER" -e "DB_PASSWORD"
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`

下面是一个将php变量传递给bash而无需解析的通用方法示例:

#!/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
#/bin/bash
源$DB_NAME-$(日期+%Y%m%d%H%m%S)。sql.gz
用几句话解释算法:
  • 运行你的php
  • 将变量打印为var=value
  • 源输出
  • 在bash中使用变量

  • 如果您试图转储MySQL数据库,还可以使用
    wp cli db export
    函数:

    wp db export --path=PATHTOYOURWP
    

    虽然这是完美的作品,它揭示了很多额外的数据,我不需要,并将需要修改,以避免有更多的数据“您可以将`| grep DB ``添加到该文件的末尾以获取数据库信息。您必须确保文件名正确,但这正是我需要它做的,谢谢您在cat上的提示:没有必要将cat和grep组合在一起。你可以
    grepdb_NAME wp config php
    。这显示了数据,但实际上没有回答上面Femi的anwser doesGreat这个问题。这就是我要找的。感谢您使用wp-cli,我强烈建议您使用wp-cli,因为它允许您编写许多任务,特别是如果您有多个wordpress站点的话。我建议使用wp cli config get命令:
    wp cli config get DB_NAME | DB_USER | DB_PASSWORD | wp_HOME | wp_SITEURL
    wp db export --path=PATHTOYOURWP