0

I have to take a data dump from my postgres database.

How do I log in to the postgres home ? . I have the following script but it doesn't work :

#!/bin/sh$                                                                      
export PASSWORD= something                                                      
echo $PASSWORD | sudo -S su postgres                                                                                                                 
pg_dump somedb > dump.txt+`date +%Y-%m-%d`          

However when I run this script I do not get logged to postgres@gauss:$ at the same time script doesn't throw an error. Is there something I am doing wrong here ?

2
  • Is your password followed by a newline char? Commented May 26, 2013 at 16:16
  • Is there really a space after the = for you password? Commented May 26, 2013 at 16:30

2 Answers 2

2

The reason your script fails is that the line

 echo $PASSWORD | sudo -S su postgres

causes su to fork a subordinate shell. That shell tries to read from the standard input which has already been exhausted by sudo -S in reading the password. When the shell finds no more input (EOF) it exits. The next line of your script then executes as if that quoted line never happened, and therefore runs under your UID.

See j.hloetzek's answer for a much better way to do what you want.

Also the script as pasted has a two syntax errors in it, but you shouldn't use that approach anyway.

Sign up to request clarification or add additional context in comments.

Comments

0

You cannot pipe the password to the sudo command, but can allow in /etc/sudoers certain commands to be run without password (check exact syntax!)

username YOURUSERNAME = NOPASSWD: /sbin/su postgres

2 Comments

"The -S (stdin) option causes sudo to read the password from the standard input instead of the terminal device. The password must be followed by a newline character." but that's not the actual flaw. However, modifying sudoers is much better than sticking a password in a script.
Neither did I so I looked it up. It's probably a bad idea (I can't think of a use-case which isn't insecure) which is why both you and I assumed it didn't exit.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.