在bash中捕获psql(PostgreSQL)命令错误,可以使用泛型,对sql无动于衷

问题描述 投票:0回答:1

我想在bash中捕获PostgreSQL错误。

例如:

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

我想要的东西可以捕获任何类型的postgres错误(不仅是为了创建)和echo错误

如果出现错误return 1

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

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

bash postgresql postgresql-10
1个回答
2
投票

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

$ 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
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.