如何使用shell脚本连接到postgresql数据库

Gau*_*put 4 shell psql

我想编写一个shell脚本来运行这些命令.我通常使用如下命令从终端连接

    //first go to the directory 
     cd /opt/novell/sentinel/3rdparty/postgresql/bin/
    // then type following
     export LD_LIBRARY_PATH=/opt/novell/sentinel/3rdparty/postgresql/lib/
    // then fire following command 
     ./psql --host 127.0.0.1 --port 5432 --dbname=SIEM --username=dbauser
     Password for user dbauser: ****
Run Code Online (Sandbox Code Playgroud)

hoo*_*oke 7

为什么不通过添加到.profile这些行来更新PATH并永久导出LD_LIBRARY_PATH :

PATH=/opt/novell/sentinel/3rdparty/postgresql/bin/:$PATH
export LD_LIBRARY_PATH=/opt/novell/sentinel/3rdparty/postgresql/lib/
Run Code Online (Sandbox Code Playgroud)

然后使用脚本连接DB,如下所示

#!/bin/sh
psql --host=127.0.0.1 --port=5432 --dbname=SIEM --username=dbauser
Run Code Online (Sandbox Code Playgroud)

运行脚本后,系统将询问您密码.

如果您不想每次都输入密码,可以使用密码文件.pgpass(详见文档 ),只需添加到~/.pgpass以下行:

127.0.0.1:5432:SIEM:dbauser:your_password
Run Code Online (Sandbox Code Playgroud)

安全,不允许任何访问世界或团体:

chmod 0600 ~/.pgpass.
Run Code Online (Sandbox Code Playgroud)

在此之后,您可以使用上面的脚本连接到您的数据库而无需密码提示.