Last active
August 12, 2022 14:30
-
-
Save joseluisq/7ae5d2fb075cebd9bd40adfaaded1f0d to your computer and use it in GitHub Desktop.
Bash script for executing MySQL query strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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