Script stops when user is changed

2

1

I am trying to create a script that logs as a different user to create a database backup. So far I have encountered a few problems, such as having to input sudo password, or not being able to bypass the password prompt for the PostgreSQL database credentials.

My script does the following:

#!/bin/bash
sudo su - postgres
cd /opt/app/backup
pg_dump --username=admin dbName > file.gz

When I run this script, it changes my local user to the postgres user as expected, but it does not execute the other lines until I type in logout. The prompt becomes stuck on:

-bash-4.1$

Any help would be greatly appreciated. I am using RedHat.

Lucas Brito

Posted 2015-03-04T22:24:59.130

Reputation: 23

Answers

0

Just a preface, but why you are even running this script with sudo or even switching users? I assume you want it to run in the background, right? Then why not just set a cron job for the postgres user? Or why are you even switching to the postgres user at all? Why not just run the backups as your regular user? The user on the actual Linux system itself and the postgres database credentials are two different things you know.

That said, onto your specific question:

When I run this script, it changes my local user to the postgres user as expected…

Are you sure that is what happens? Is the output of whoami actually postgres? I say that because I am not too clear on this line:

sudo su - postgres

That sudo su - switches the user to the root and then the postgres that follows it… Unsure how the shell would handle that? In my mind it should simply be this:

sudo su postgres

Also, looking at the answer “Barmar” provides here on Stack Overflow, it seems like using “here documents”—a.k.a. “here docs—might be another tact to pip commands to that user. Knowing that, here is a rewrite of your script that might work:

#!/bin/bash
sudo su postgres <<'EOF'
cd /opt/app/backup
pg_dump --username=admin dbName > file.gz
EOF

JakeGould

Posted 2015-03-04T22:24:59.130

Reputation: 38 217