3

I'm trying to create a postgres role and password from bash. However, it seems I'm struggling with the escaping of quotes.

Running:

$ sudo su - postgres -c '''psql -c "CREATE USER testuser WITH PASSWORD 'somepass';" '''

Produces:

ERROR:  syntax error at or near "somepass"
LINE 1: CREATE USER testuser WITH PASSWORD somepass;

Other unsuccessful variations I've tried;

sudo su - postgres -c """psql -c "CREATE USER testuser WITH PASSWORD 'somepass';" """
sudo su - postgres -c $''' psql -c "CREATE USER testuser WITH PASSWORD \'pass\';" '''

How can I deal with the nested quotes, and get postgres to create the role from cli?

2 Answers 2

3

''' and $''' are pointless. They're equivalent to '.

That's because '''foo' is parsed as an empty quoted string '' immediately followed by another quoted string 'foo', which is just foo.

To get a single ' into a single-quoted shell string, use '\'':

sudo su - postgres -c 'psql -c "CREATE USER testuser WITH PASSWORD '\''somepass'\'';"'

The reason this works: 'foo'\''bar' is parsed as a quoted part ('foo') followed by an unquoted but backslash-escaped character (\') followed by another quoted part ('bar'). These are all concatenated to form foo'bar.

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

Comments

1

You can avoid all quoting problems by using a here-document :

#!/bin/sh
sudo su - postgres -c psql <<OMG
CREATE USER testuser WITH PASSWORD 'somepass';
-- DROP USER testuser ;
OMG

BTW: you dont need a script for this, it will work just as well in an interactive shell. (I just used the script to test it)

Comments

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.