Shell integration
For people not familiar with MySQL syntax, here are handy shell functions which are easy to remember and use (to use them, you need to load the shell functions included further down).
Here is example:
$ mysql-create-user admin mypass
| CREATE USER 'admin'@'localhost' IDENTIFIED BY 'mypass'
$ mysql-create-db foo
| CREATE DATABASE IF NOT EXISTS foo
$ mysql-grant-db admin foo
| GRANT ALL ON foo.* TO 'admin'@'localhost'
| FLUSH PRIVILEGES
$ mysql-show-grants admin
| SHOW GRANTS FOR 'admin'@'localhost'
| Grants for admin@localhost
| GRANT USAGE ON *.* TO 'admin'@'localhost' IDENTIFIED BY PASSWORD '*6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4' |
| GRANT ALL PRIVILEGES ON `foo`.* TO 'admin'@'localhost'
$ mysql-drop-user admin
| DROP USER 'admin'@'localhost'
$ mysql-drop-db foo
| DROP DATABASE IF EXISTS foo
To use above commands, you need to copy&paste the following functions into your //rc// file (e.g. [[https://github.com/kenorb/dotfiles/blob/master/.bash_profile|.bash_profile]]) and reload your shell:
# Create user in MySQL/MariaDB.
mysql-create-user() {
[ -z "$2" ] && { echo "Usage: mysql-create-user (user) (password)"; return; }
mysql -ve "CREATE USER '$1'@'localhost' IDENTIFIED BY '$2'"
}
# Delete user from MySQL/MariaDB
mysql-drop-user() {
[ -z "$1" ] && { echo "Usage: mysql-drop-user (user)"; return; }
mysql -ve "DROP USER '$1'@'localhost';"
}
# Create new database in MySQL/MariaDB.
mysql-create-db() {
[ -z "$1" ] && { echo "Usage: mysql-create-db (db_name)"; return; }
mysql -ve "CREATE DATABASE IF NOT EXISTS $1"
}
# Drop database in MySQL/MariaDB.
mysql-drop-db() {
[ -z "$1" ] && { echo "Usage: mysql-drop-db (db_name)"; return; }
mysql -ve "DROP DATABASE IF EXISTS $1"
}
# Grant all permissions for user for given database.
mysql-grant-db() {
[ -z "$2" ] && { echo "Usage: mysql-grand-db (user) (database)"; return; }
mysql -ve "GRANT ALL ON $2.* TO '$1'@'localhost'"
mysql -ve "FLUSH PRIVILEGES"
}
# Show current user permissions.
mysql-show-grants() {
[ -z "$1" ] && { echo "Usage: mysql-show-grants (user)"; return; }
mysql -ve "SHOW GRANTS FOR '$1'@'localhost'"
}