【问题标题】:Centos Bash Script with Postrgres database带有 Postgres 数据库的 Centos Bash 脚本
【发布时间】:2016-01-28 12:08:31
【问题描述】:

希望有人可以帮助我解决我试图在 CentOS 机器上运行的这个 bash 脚本。我在 FreeBSD 上写过这样的脚本

#!/bin/sh
setenv code1 "grant select on "
setenv code2 " to testusr"

echo setting read only access
foreach table (table1 table2 table3)
  psql -c "psql -d databasename -c '$code1$table$code2'"
end
echo finished

然后我改为跟随但它不起作用。它抱怨倒数第三行 (sudo su postgres) 有人可以帮忙吗?

#!/bin/bash
set env code1 "grant select on "
set env code2 " to testusr"

echo setting read only access
for table in 'table1 table2 table3'
  sudo su postgres -c "psql -d databasename -c '$code1$table$code2'"
do;
echo finished

任何帮助将不胜感激。

【问题讨论】:

  • 你的问题到底是什么?
  • 第一个脚本看起来像csh,尽管有/bin/sh shebang 行。

标签: bash postgresql shell centos


【解决方案1】:

除了一些语法错误之外,您还应该使用sudo 来运行psql。除此之外,它还减少了嵌套引用的数量,因为您不再需要将整个 psql 命令放入单个字符串中作为 su-c 选项的参数。

#!/bin/bash
code1="grant select on "
code2=" to testusr"

echo setting read only access
for table in table1 table2 table3; do
  sudo -u postgres psql -d databasename -c "$code1 $table $code2"
done
echo finished

【讨论】:

  • 我仍然收到错误 ./test.sh: line 8: syntax error near unexpected token `source' table1 table2 table3
  • 你在运行上面的代码吗?我根本没有使用“源”这个词,所以我看不出你是如何从我的代码中得到这个错误的。
  • 效果很好。那是我的错误,你是对的。非常感谢您的帮助:)
【解决方案2】:

语法错误,试试:

#!/bin/bash
code1="grant select on"
code2="to testusr"

echo "setting read only access"
for table in 'table1 table2 table3'
  su postgres -c "psql -d databasename -c $table"
do;
echo "finished"

【讨论】:

  • 谢谢。它再次给我语法错误:意外标记附近的语法错误su' ./test.sh: line 16: su postgres -c "p​​sql -d databasename '$code1$table$code2'"'
  • 您还需要从 for 循环中的列表中删除引号。
  • 你是对的。我从循环中删除了引号,但同时添加了 $code1 和 $code2 但这些表是 postgres 表,所以它不起作用。看来我可能需要用不同的逻辑重写脚本
猜你喜欢
  • 1970-01-01
  • 2014-07-28
  • 2013-08-15
  • 1970-01-01
  • 2021-01-15
  • 1970-01-01
  • 2019-06-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多