Postgresql 如何在Ubuntu 16上的shell脚本中使用postgres用户

Postgresql 如何在Ubuntu 16上的shell脚本中使用postgres用户,postgresql,shell,ubuntu,psql,Postgresql,Shell,Ubuntu,Psql,我正在尝试将Debian7上运行的shell脚本集改编为Ubuntu 16 除了执行PosgreSQL数据库命令的部分之外,我成功地更改了所有的部分 以前版本的脚本包含以下行: service postgresql restart psql -q -U postgres -c "DROP DATABASE IF EXISTS db_crm" -o $log &> /dev/null psql -q -U postgres -c "CREATE DATABASE db_crm" -

我正在尝试将Debian7上运行的shell脚本集改编为Ubuntu 16

除了执行PosgreSQL数据库命令的部分之外,我成功地更改了所有的部分

以前版本的脚本包含以下行:

service postgresql restart

psql -q -U postgres -c "DROP DATABASE IF EXISTS db_crm" -o $log &> /dev/null
psql -q -U postgres -c "CREATE DATABASE db_crm" -o $log &> /dev/null
当我试图在Ubuntu16上运行上述psql时,操作系统无法识别该命令。使用sudo调用脚本是很重要的

我找到了一种在Ubuntu 16上只运行数据库脚本的方法,改变了代码:

service postgresql restart

su postgres <<EOF

psql -c "DROP DATABASE IF EXISTS db_crm" -o $log &> /dev/null
psql -c "CREATE DATABASE db_crm" -o $log &> /dev/null
即使将EOF替换为下一行,错误仍在继续


如果有一种在shell脚本中使用psql而不使用EOF的方法会更好。

脚本失败的原因是您在输入结束时忘记了
EOF

su postgres <<EOF

psql -c "DROP DATABASE IF EXISTS db_crm" -o $log &> /dev/null
psql -c "CREATE DATABASE db_crm" -o $log &> /dev/null

EOF   #<<<--- HERE

脚本失败的原因是您忘记了输入结束时的
EOF

su postgres <<EOF

psql -c "DROP DATABASE IF EXISTS db_crm" -o $log &> /dev/null
psql -c "CREATE DATABASE db_crm" -o $log &> /dev/null

EOF   #<<<--- HERE
#! /usr/bin/env bash

# PGPASSWORD='' #(set this to stop password prompts, but it's insecure)
PSQL="psql -q -U postgres -o $log"  #TODO define $log
TMPFILE="/tmp/sql-tmp.`date +%Y%m%d_%H%M%S_%N`.sql"

# TODO - check $TMPFILE does not exist already

echo "DROP DATABASE IF EXISTS db_crm;" > "$TMPFILE"
echo "CREATE DATABASE db_cr;" >> "$TMPFILE"
# ... etc.

# run the command, throw away any stdout, stderr
PSQL < "$TMPFILE" 2>&1 > /dev/null

# exit with the psql error code
err_code=$?
exit $?