0

I'm writing a bash/shell script that has a psql database connection and the program fails with psql: FATAL: database "foo" does not exist. This is fine because the program exits since it doesn't exist, but what I would like to do instead is trap or capture that FATAL message and perhaps echo or do something else.

Like if message == "database "foo" does not exist; then echo or run another function.

Here's my line of code that does db connection:

PGPASSWORD=$TARGET_PW "$PSQL" -h "$HOST2" -U masteruser -d "$database" -p 5439 << EOF 
        \a
        \t
        \o $LISTNEW
    SELECT column_name
    FROM information_schema.columns
    WHERE table_schema = '$SCHEMAMAIN'
    AND table_name   = '$TBL'
    order by ordinal_position;
EOF

Can I get an example of how to do this? thanks.

noober
  • 1,427
  • 3
  • 23
  • 36

1 Answers1

2

Edited version

The best way to redirect a command’s stderr to a variable is

errMsg=$(some_command 2>&1 >/dev/tty)

so, for clarity, I would define a function around your original code

function my_psql () {
PGPASSWORD=$TARGET_PW "$PSQL" -h "$HOST2" -U masteruser -d "$database" -p 5439 << EOF 
        \a
        \t
        \o $LISTNEW
    SELECT column_name
    FROM information_schema.columns
    WHERE table_schema = '$SCHEMAMAIN'
    AND table_name   = '$TBL'
   order by ordinal_position;
EOF
}

You are running your command in a script, and don’t want to redirect to /dev/tty. So:

# Save the script’s stdout in fd #10
exec 10>&1
# my_psql sends its stderr to the variable and its stdout to fd #10
errMsg=$(my_psql 2>&1 1>&10)

Now, you can do with the output of a non-failed command whatever you did before. You might also want to close fd #10 with exec 10>&- at a certain point.

Defining a function can also be useful to get rid of the $PSQL variable. Many of us follow the principle that variables are for values, functions for commands and have reasons not to store commands to be executed into variables, but this is irrelevant to your question and is more a matter of tastes...

See also this and this SO question.

Community
  • 1
  • 1
Dario
  • 2,673
  • 20
  • 24