Search code examples
phpscriptingapostrophe

how to use apostrophe ( ' inside " and then inside ' )


I need to issue this command via sudo in php. But sudo needs to have the command inside apostrophes.

psql -c "create database radek with encoding 'unicode';" -U edumate template1

so

sudo -su postgres 'psql -c "create database radek with encoding ''unicode'';" -U edumate template1'

gives me an error

ERROR:  syntax error at or near "unicode"
LINE 1: create database radek with encoding unicode;
                                            ^

I'd say that the error happens because unicode is enclosed by '. And sudo command is enclosed by ' too.

UPDATE

escaping unicode \'unicode\' doesn't work. I get > and it hangs there for ever....

UPDATE2

the final php code is like

exec("sudo -su postgres 'psql -c \"create database " . $db . " with encoding '\"'\"'unicode'\"'\"';\" -U edumate template1'", $output); 

thanks to @Matthew Scharley


Solution

  • It's a bit weird, but what's happening with your double apostrophe is that it's closing the string then reopening it again, which gains you a net of nothing. The solution is the following:

    sudo -su postgres 'psql -c "create database radek with encoding '"'"'unicode'"'"';" -U edumate template1'
    

    ie. Put the apostrophe in double quotes between the close and open. This will work in at least bash type shells, but I don't use others to know how they work.