views:

56

answers:

3

can I change/su user in the middle of a script?

if [ "$user" == "" ]; then
  echo "Enter the table name";
  read user
fi

gunzip *
chown postgres *
su postgres 
dropdb $user
psql -c "create database $user with encoding 'unicode';" -U dbname template1
psql -d $user -f *.sql
+6  A: 

You can, but bash won't run the subsequent commands as postgres. Instead, do:

su postgres -c 'dropdb $user'

The -c flag runs a command as the user (see man su).

Mark Trapp
thank you @Mark Trapp
Radek
+2  A: 

No you can't. Or atleast... you can su but su will simply open a new shell at that point and when it's done it will continue with the rest of the script.

One way around it is to use su -c 'some command'

WoLpH
+3  A: 

Not like this. su will invoke a process, which defaults to a shell. On the command line, this shell will be interactive, so you can enter commands. In the context of a script, the shell will end right away (because it has nothing to do).

With

su user -c command

command will be executed as user - if the su succeeds, which is generally only the case with password-less users or when running the script as root.

Use sudo for a better and more fine-grained approach.

mvds