开发者

how to run shell script command with double quotes in the argument?

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' = ps开发者_Go百科ql -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'


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜