I need to run this command,
psql -c "create database $var with encoding 'unicode';" -U edumate template1
from the script under a different user. The su
syntax is su postre -c 'some command'
, so there are other quotes required. Also, please note that the psql
command has the $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).
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'