Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple quotes in command

Tags:

bash

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 ?

like image 831
bux Avatar asked Nov 30 '25 05:11

bux


2 Answers

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\';"'
    
like image 123
ruakh Avatar answered Dec 02 '25 04:12

ruakh


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
like image 43
chepner Avatar answered Dec 02 '25 04:12

chepner