如何在参数中使用双引号运行shell脚本命令?

Rad*_*dek 2 shell double-quotes

我需要运行这个命令

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

从不同用户下的脚本.su语法是su postre -c 'some command'如此,还需要另一个引号.另请注意,psql命令$var里面有变量.

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

并且'某些命令'也必须用引号括起来(我猜)

ret*_*ops 6

你可以随时使用一个技巧,让shell接受单个参数,同时包含单引号和双引号.因为shell不会让你转义引号,你需要将它转换为多个邻接的引用字符串,根据需要在单引号和双引号之间切换以保护内部.这很难看,但它确实有效.例如,拥有

   He said "It's done"
Run Code Online (Sandbox Code Playgroud)

是一个单一的论点,你可以接近三个字符串:

   'He said "It'   - protect this substring with single quotes
   "'"             - protect this substring with double quotes
   's done"'       - protect this substring with single quotes
Run Code Online (Sandbox Code Playgroud)

要得到:

   'He said "It'"'"'s done"'
Run Code Online (Sandbox Code Playgroud)

在你的情况下会产生一个非常丑陋:

su postre -c 'psql -c "create database '"$var with encoding 'unicode';"'" -U edumate template1'
Run Code Online (Sandbox Code Playgroud)