3

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?

5

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.