Categories
Tech TIL

TIL: How to pass MySQL queries as variables in Bash

Note: I also learned how to handle query blocks with Bash here documents. Most of what I’ve done in the past with MySQL and Bash has been limited to single-line selects, so Yay!, learning.

#!/bin/bash

db_server=servername.local
db_user=millhouse
db_pass=derpderpderp

user_id=$(mysql -u$db_user -p$db_pass $db_server <<GET_USER_ID
USE main;
SELECT user_id FROM users WHERE username="dave";
GET_USER_ID
)

echo "Dave's User ID is $user_id"

It’s the small things in life…