1

I am working on a script that creates a Postgres user with a variable input from a source file. As the user 'root' I run the following script:

su - postgres <<'EOF'
. /var.src
psql
CREATE ROLE john;
ALTER USER john WITH PASSWORD '$JOHNPASSWORD';
ALTER ROLE john WITH LOGIN;
CREATE DATABASE john;
ALTER DATABASE john OWNER TO john;
\q
EOF

I'm creating a user john and a database john, however john's password is in the var.src. Everywhere I look I get commands similar to this:

sudo -u postgres psql -c "ALTER USER john WITH PASSWORD '$JOHNPASSWORD';"

Replacing the password with $JOHNPASSWORD requires an escape I assume. I have tried escaping the single quote with a backslash, double-quotes, etc. Nothing. I haven't been able to find how I can escape the single quote so that it can read the variable from var.src.

Maybe it has something to do with how I'm approaching this entirely?

  • Is your last command in script ? – Anwar Aug 21 '16 at 17:16
  • Yes. I am currently exploring options for exporting but I'm not sure – KDoe Aug 21 '16 at 17:17
  • I ran your script and your command in the terminal. It works! how exactly have you tried to execute them? – Anwar Aug 21 '16 at 17:18
  • I run it from my home directory using ./myscript in /root/myscript.sh. The problem is in var.src the variable is JOHNPASSWORD=myc00lpassword. But Postgres processes the user with the password $JOHNPASSWORD not myc00lpassword. It sets the variable as a string. – KDoe Aug 21 '16 at 17:34
  • you don't need to say the exact password. remove it and use some fake one. are you using it with root? – Anwar Aug 21 '16 at 17:36
0

I found something that helped. I supplied the password alter command after the script broke out of the EOF. So here is what worked for me:

    su - postgres <<'EOF'
    . /var.src
    psql
    CREATE ROLE john;
    ALTER ROLE john WITH LOGIN;
    CREATE DATABASE john;
    ALTER DATABASE john OWNER TO john;
    \q
    EOF

    . /var.src
    sudo -u postgres psql -c "ALTER USER john WITH PASSWORD '$JOHNPASSWORD';"

This is because I called the variable file again after the EOF. I'm sure that has to do with my previous assumption of escaping the quote. But this works also.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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