Skip to content

Instantly share code, notes, and snippets.

@disaac
Forked from joseluisq/config.sh
Created February 3, 2020 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save disaac/1e29509ebc939cdbf3f49625ac38091b to your computer and use it in GitHub Desktop.
Save disaac/1e29509ebc939cdbf3f49625ac38091b to your computer and use it in GitHub Desktop.
Bash script for executing MySQL query strings
# Database configuration
########################
# Use this file as database custom configuration file
DB_NAME='mydb'
DB_HOST='127.0.0.1'
DB_USER='usr'
DB_PASSWD='pwd'
# MySQL execution query utility
###############################
# A simple script for executing MySQL queries
# This script needs a previous `config.sh` file created in the current directory
CWD="$(dirname "$0")"
QUERY=$1
if [ -z "$DB_HOST" ]; then
echo "No DB_HOST supplied!"
exit 1
fi
if [ -z "$DB_NAME" ]; then
echo "No DB_NAME supplied!"
exit 1
fi
if [ -z "$DB_USER" ]; then
echo "No DB_USER supplied!"
exit 1
fi
if [ -z "$DB_PASSWD" ]; then
echo "No DB_PASSWD supplied!"
exit 1
fi
if [[ -z "$QUERY" ]]; then
echo "No query string supplied!"
exit 1
fi
echo
echo "Query to execute:"
cat <<EOF
${QUERY}
EOF
# Connect to database and execute the current query string
# Note that `SHOW FULL PROCESLIST` is activated (feel free to customize it)
mysql -h "$DB_HOST" -u "$DB_USER" -p"$DB_PASSWD" <<EOF
SHOW FULL PROCESSLIST;
USE ${DB_NAME};
${QUERY}
SHOW PROFILES;
EOF
echo
#!/bin/bash
# Execution query example
#########################
CWD="$(dirname "$0")"
# 1) Verify if the config.sh file exists
if [ ! -f $CWD/config.sh ]; then
echo "Please create a custom 'config.sh' file at '$CWD' directory."
exit 1
fi
# 2) Load the `config.sh` file with the database variables
source $CWD/config.sh
# 3) Define some cool query string
q="
SELECT * FROM users
WHERE id = 10000000;
"
# 4) Execute the current query string
env \
DB_NAME=$DB_NAME \
DB_HOST=$DB_HOST \
DB_USER=$DB_USER \
DB_PASSWD=$DB_PASSWD \
$CWD/query.sh "${q}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment