-2

Hope someone can help me with this bash script which I am trying to run on a CentOS machine. I wrote a script on FreeBSD like this

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

Then I changed to following but it did not work. It complains for the third last line (sudo su postgres) Can someone help with this please?

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

Any help will be much appreciated.

2
  • What exactly is your question? Oct 28, 2015 at 16:07
  • The first script looks like csh in spite of the /bin/sh shebang line.
    – tripleee
    Nov 4, 2015 at 7:17

2 Answers 2

0

Aside from a few syntax errors, you should also use sudo to run psql. Among other things, it reduces the amount of nested quoting, as you no longer have to fit the entire psql command in a single string as the argument to su's -c option.

#!/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
3
  • I still getting error ./test.sh: line 8: syntax error near unexpected token `source' table1 table2 table3 Oct 28, 2015 at 17:41
  • 1
    Are you running the code above? I didn't use the word "source" at all, so I don't see how you could get that error from my code.
    – chepner
    Oct 28, 2015 at 18:23
  • It works great. That was my error, you were right. Thanks very much for your help :) Oct 28, 2015 at 19:15
-1

The syntax is wrong, try:

#!/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"
3
  • Thanks. It is again giving me syntax error: syntax error near unexpected token su' ./test.sh: line 16: su postgres -c "psql -d databasename '$code1$table$code2'"' Oct 28, 2015 at 16:46
  • You also need to drop the quotes from the list in the for loop.
    – chepner
    Oct 28, 2015 at 17:12
  • You are right. I dropped the quotes from the loop but same time added $code1 and $code2 but the tables are postgres tables, so it is not working. Seems i may need to re-write the script with a different logic Oct 28, 2015 at 17:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.