Bash – How to save psql error message output in bash variable

basherror handlingpostgresqlshell-scriptvariable

I have a script that runs several different psql statements. I'm trying to capture the error output from psql when password entered is incorrect.
The password is entered in before the check (and when correct, the psql statements execute successfully)

I've tried the following:

pwcheck=`psql -q -U postgres -h $ip -d $database;`
echo "error message: $pwcheck"

When I enter an incorrect password to check it, the error messages are output but the variable is empty.

psql: FATAL:  password authentication failed for user "postgres"
FATAL:  password authentication failed for user "postgres"
error message:

Ideally, I'd like to save the error message to a variable and not print my own error message/prompt and not display the psql errors at all.

How can I store either of these error messages in a bash variable?

Best Answer

You can't, directly. At least, not without either commingling it with or discarding standard output. However, there is a way!

#!/bin/bash
errorlog=$(mktemp)
trap 'rm -f "$errorlog"' EXIT
pwcheck="$(psql -q -U postgres -h $ip -d $database 2> "$errorlog")"
if [[ 0 -ne $? ]]; then
    echo "Something went wrong; error log follows:"
    cat "$errorlog"
fi
Related Question