A Bash function to check Drupal database sizes

Drupal 8Drupal 7

At times I'd like to check the size of databases used by Drupal.

But I don't like to launch apps like phpMyAdmin and Sequel Pro only for that. So I wrote a tiny Bash function to check Drupal database sizes.

## Check the size of database used by Drupal (MySQL is expected).
function drupal_database_get_size {
  local drupal_db_name;
  drupal_db_name="$(drush sql-conf | grep "database" | grep -Eo "\S+$")"
  if [[ -z "$drupal_db_name" ]]; then
    echo "usage: run this command under a drupal instance directory."
    return
  fi

  $(drush sql-connect) -e "SELECT table_schema AS \"Database\", SUM(ROUND(((data_length + index_length) / 1024 / 1024), 2)) AS \"Size in MB\" FROM information_schema.TABLES  WHERE table_schema = \"$drupal_db_name\""
}

Let's give it a try.

Without a Drupal instance:

$ cd /path/out/of/drupal
$ drupal_database_get_size
Unable to load class Drush\Sql\Sql exception 'Drush\Sql\SqlException' with message 'Unable to find a matching SQL Class. Drush cannot find your database connection details. ...
...
usage: run this command under a drupal instance directory.

With a Drupal instance:

$ cd /path/to/drupal
$ drupal_database_get_size
mysql: [Warning] Using a password on the command line interface can be insecure.
+---------------+------------+
| Database      | Size in MB |
+---------------+------------+
| db_for_drupal |     119.20 |
+---------------+------------+

Woo-hoo!

You can use this function by adding the definition above into your Bash config file such as ~/.bashrc.


アバター
後藤隼人 ( ごとうはやと )

Python や PHP を使ってソフトウェア開発やウェブ制作をしています。詳しくはこちら