【问题标题】:Creating a oneliner to import database创建一个单行器来导入数据库
【发布时间】:2017-03-05 21:37:20
【问题描述】:

我正在尝试在 Linux 中创建一个单行器,它将从 wp-config.php 收集数据库主机、数据库名称、用户名和密码,并将其组合成一行,我可以在其中导入带有 .sh 文件的数据库。

我需要收集的代码块是:

/** The name of the database for WordPress */
define('DB_NAME', 'database_name_here');

/** MySQL database username */
define('DB_USER', 'username_here');

/** MySQL database password */
define('DB_PASSWORD', 'password_here');

/** MySQL hostname */
define('DB_HOST', 'localhost');

我要创建的行是:

mysql -h localhost -u username_here --password="password_here" database_name_here < db-backup.sql

我是新手,所以我尝试做的是:

grep DB_HOST DB_USER wp-config.php | cut -d "'" -f4 | awk '{print "mysql -h "$0;}' 这个开始是有效的,但是当我想向字符串添加更多信息时,我只是得到最后一部分。

如何编写此代码以获得包含所有信息的完整行?

【问题讨论】:

    标签: linux ubuntu awk grep cut


    【解决方案1】:
    MYSQLPWD=$(cat wp-config.php |grep DB_PASSWORD | cut -d \' -f 4)
    MYSQLUSR=$(cat wp-config.php |grep DB_USER | cut -d \' -f 4)
    MYSQLDBNAME=$(cat wp-config.php |grep DB_NAME | cut -d \' -f 4)
    HT="localhost"
    
    echo $MYSQLPWD
    echo $MYSQLUSR
    echo $MYSQLDBNAME
    echo $HT
    
    mysql -h$HT -u$MYSQLUSR -p$MYSQLPWD $MYSQLDBNAME <  $MYSQLDBNAME
    

    【讨论】:

      【解决方案2】:

      不是单行的,但适用于您的简单示例

      DB_PASSWORD=$(grep DB_PASSWORD wp-config.php | cut -d "'" -f4)
      DB_USER=$(grep DB_USER wp-config.php | cut -d "'" -f4)
      DB_NAME=$(grep DB_NAME wp-config.php | cut -d "'" -f4)
      DB_HOST=$(grep DB_HOST wp-config.php | cut -d "'" -f4)
      
      echo "mysql -h $DB_HOST -u $DB_USER --password=\"$DB_PASSWORD\" $DB_NAME"
      

      注意事项:你不需要 awk,你只是用它来连接字符串,所以我删除了它。而且对输入文件中相关行的检测并不完善,可能会被很多东西弄糊涂,比如输入文件中是否有注释

      /** we are using blabla as DB_NAME because <reasons> **/ 
      

      它会将该行检测为与 DB_NAME 匹配。 此外,有一条匹配线也很重要。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多