在 bash 中捕获一个 psql(PostgreSQL) 命令错误,可以使用通用的,与 sql 无关

Catch a psql(PostgreSQL) command error in bash, that can be used generic, indifferent of the sql

我想在 bash 中捕获 PostgreSQL 错误。

例如:

function create_database:
    sudo -u postgres psql -c "CREATE DATABASE  WITH OWNER ;"

我想要一些可以捕获任何类型的 postgres 错误(不仅用于创建)和 echo 错误

同样在错误的情况下return 1

如果我使用: $RESULT=$(sudo -u postgres psql -c "CREATE DATABASE WITH OWNER ;")

我从psql得到了答案,但是是特定于操作的,所以我必须为每个SQL命令做字符串匹配。

查看语句是否成功非常简单:只需检查 return 代码即可。

$ sudo -u postgres psql -c 'melect 32'
ERROR:  syntax error at or near "melect"
LINE 1: melect 32
        ^
$ echo $?
1

$ sudo -u postgres psql -c 'DROP TABLE not_exists'
ERROR:  table "not_exists" does not exist
$ echo $?
1

$ sudo -u postgres psql -c 'SELECT 42'
 ?column? 
----------
       42
(1 row)

$ echo $?
0

因此您的代码可以执行如下操作:

sudo -u postgres psql -c "..." >/tmp/result 2>&1
if [ $? -ne 0 ]; then
    echo /tmp/result >>logfile
    rm -f /tmp/result
    exit 1
else
    rm -f /tmp/result
fi