postgresql - 如何在 Ubuntu 16 的 shell 脚本中使用 postgres 用户

标签 postgresql shell ubuntu psql

我正在尝试调整为在 Debian 7 上运行而制作的 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

当我尝试在 Ubuntu 16 上按上述方式运行 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

但是,这个脚本在被主脚本调用时不起作用。显示以下消息:

here-document at line 41 delimited by end-of-file (wanted 'EOF')

syntax error: unexpected end of file

即使将 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

一个简单的方法是将您的命令放入一个临时文件中,然后将其重新定向到 psql 中。显然你不希望它因密码提示而停止,在这种情况下要么使用不需要它的用户,要么设置 $PGPASSWORD - 或者在脚本开头提示 - 有有很多方法。

#! /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 $?

关于postgresql - 如何在 Ubuntu 16 的 shell 脚本中使用 postgres 用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43399438/

相关文章:

linux - shell中 `find . -name`和 `find -name`的区别?

java - "Where is the framework?" Play 错误!框架

bash - 发送击键到 Dockerfile,Ubuntu

ubuntu - NAT MASQUERADE 响应数据包未返回专用网络

django - Pycharm错误: Improperly configured

linux - 如何从 shell 设置管道尺寸?

postgresql - 查看表的时间戳字段中有哪些唯一日期的最快方法?

linux - 连接错误运行时脚本linux

ruby-on-rails - 使用 zeus : Postgres is being accessed by other users 进行 cucumber 和 RSpec 测试

sql - 如何在 SQL 中取 NTiles 的平均值?