Reputation: 7799
I'm trying to execute command with multiple quotes, but seems problematic:
sudo su - postgres -c 'psql -U postgres -c "alter user postgres with password 'dummy';"'
ERROR: syntax error at or near "dummy"
LINE 1: alter user postgres with password dummy;
^
If i dot the same command in two step, no problems:
sudo su - postgres
postgres@courgette:~$ psql -U postgres -c "alter user postgres with password 'dummy';"
ALTER ROLE
How correctly quote "dummy" in one line first exemple ?
Upvotes: 3
Views: 2442
Reputation: 532238
Instead of running su
with sudo
, just run psql
directly. This eliminates one level of quotes, as well as the need to specify the user with the -U
option:
sudo -u postgres psql "alter user postgres with password 'dummy';"
If you can't do that for whatever reason, use a here document to eliminate a level of quotes:
sudo su - postgres -U postgres <<EOF
alter user postgres with password 'dummy'
EOF
Upvotes: 2
Reputation: 183554
Per the Bash Reference Manual, §3.1.2.2 "Single Quotes":
Enclosing characters in single quotes (‘
'
’) preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.
So, you have three reasonable options:
you can exit the single-quoted bit just long enough to add a double-quoted single-quote:
sudo su - postgres -c 'psql -U postgres -c "alter user postgres with password '"'"'dummy'"'"';"'
you can use double-quotes "..."
, in which case you have to escape any internal double-quotes:
sudo su - postgres -c "psql -U postgres -c \"alter user postgres with password 'dummy';\""
you can use $'...'
(which differs from both '...
' and "..."
in that it supports a wide variety of C-style escape sequences), in which case you have to escape any internal single-quotes:
sudo su - postgres -c $'psql -U postgres -c "alter user postgres with password \'dummy\';"'
Upvotes: 10