Can I run 'su' in the middle of a bash script?
Solution 1:
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
).
Solution 2:
You can use a here document to embed multiple su
commands in your script:
if [ "$user" == "" ]; then
echo "Enter the table name";
read user
fi
gunzip *
chown postgres *
su postgres <<EOSU
dropdb $user
psql -c "create database $user with encoding 'unicode';" -U dbname template1
psql -d $user -f *.sql
EOSU