Question

I need to run this command

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

from the script under different user. The su syntax is su postre -c 'some command' so there are another quotes required. Also please note that the psql command has $var variable inside.

so 'some command' = psql -c "create database $var with encoding 'unicode';" -U edumate template1

and 'some command' must be enclosed in quotes too (I guess)

Was it helpful?

Solution

There's a trick you can use anytime you need to have the shell accept as a single argument something that has both single quotes and double quotes. Because the shell won't let you escape quotes, you need to turn it into multiple abutting quoted strings, switching between single and double quotes as needed to protect what's inside. It's ugly, but it works. For example, to have

   He said "It's done"

be a single argument, you could abut the three strings:

   'He said "It'   - protect this substring with single quotes
   "'"             - protect this substring with double quotes
   's done"'       - protect this substring with single quotes

to get:

   'He said "It'"'"'s done"'

In your case that would give a very ugly:

su postre -c 'psql -c "create database '"$var with encoding 'unicode';"'" -U edumate template1'

OTHER TIPS

You may try sudo instead of su e.g.

sudo psql -c "create database $var with encoding 'unicode';" -U edumate template1

(Note: well I havent tested exactly this command as I dont have psql with me right now)

I would enter this into a script file (enter it into an editor such as vi and save it to a file). Then, chmod +x and then do your su -c '<filename>'

If you don't want to save it to a file, then you'll have to escape your quotation marks with \" or \' inside your command depending upon which quote you decide to use with su -c

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top