使用Postrgres数据库的Centos Bash脚本

时间:2015-10-28 15:56:46

标签: bash postgresql shell centos

希望有人可以帮助我使用这个bash脚本,我试图在CentOS机器上运行。我在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

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

除了一些语法错误之外,您还应该使用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

答案 1 :(得分:-1)

语法错误,请尝试:

#!/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"