Roudy Chammas
Roudy Chammas

Reputation: 3

Write mysql error into a log file in bash

I'm writing a bash script and I want to redirect MySQL errors to a log file.

I had success with the below (ERROR 1045 (28000): Access denied for user... is being appended to the log file)

mysql -u user -pWrongpass -sN -e "query to update db;" 2>&1 | tee -a log

however, I'm not having success with this one. The error is displayed when I run the script but I don't see it in the log file.

result=$(mysql -u user -pWrongpass -sN "query to select from db;") 2>&1 | tee -a log

What's the correct syntax to put the result of a query into a variable while printing any potential error to the log file?

Thanks in advance and let me know if I'm not clear :)

Upvotes: 0

Views: 1956

Answers (1)

chepner
chepner

Reputation: 532518

You have to put the entire pipeline inside the command substitution.

result=$(mysql -u user -pWrongpass -sN "query to select from db;" 2>&1 |
         tee -a log)

Since the output of mysql is piped to tee, it is the output of tee that you need to capture in result.

Upvotes: 2

Related Questions