一个子shell执行通话过程中的一个变量举行字符串麻烦转义引号 [英] Trouble escaping quotes in a variable held string during a Sub-shell execution call
问题描述
我想从一个bash脚本中写入数据库调用和我有一个子壳剥我的报价远的问题。
I'm trying to write a database call from within a bash script and I'm having problems with a sub-shell stripping my quotes away.
这是我在做什么骨头。
#---------------------------------------------
#! /bin/bash
export COMMAND='psql ${DB_NAME} -F , -t --no-align -c "${SQL}" -o ${EXPORT_FILE} 2>&1'
PSQL_RETURN=`${COMMAND}`
#---------------------------------------------
如果我用一个回响,打印出$ {COMMAND}变量输出看起来不错:
If I use an 'echo' to print out the ${COMMAND} variable the output looks fine:
echo ${COMMAND}
屏幕输出: -
#---------------
psql drupal7 -F , -t --no-align -c "SELECT DISTINCT hostname FROM accesslog;" -o /DRUPAL/INTERFACES/EXPORTS/ip_list.dat 2>&1
#---------------
另外,如果我剪切并粘贴此屏幕输出它执行就好了。
Also if I cut and paste this screen output it executes just fine.
然而,当我尝试作为一个子shell调用中的变量要执行的命令,它给出了一个错误信息。
该错误是由psql客户端可以到报价已经从周围$ {} SQL字符串,删除的效果。
该错误表明在psql试图间preT中的SQL字符串作为参数的条件。
However, when I try to execute the command as a variable within a sub-shell call, it gives an error message. The error is from the psql client to the effect that the quotes have been removed from around the ${SQL} string. The error suggests psql is trying to interpret the terms in the sql string as parameters.
如此看来字符串和引号组成正确,但周围的$ {} SQL变量/字符串引号正在从主脚本执行通话过程中由子shell PTED间$ P $。
So it seems the string and quotes are composed correctly but the quotes around the ${SQL} variable/string are being interpreted by the sub-shell during the execution call from the main script.
我试着用各种方法逃离他们: \\,\\\\,\\\\\\,,\\'',\\'\\',.. ......
正如你可以从我'试试'的做法看,我不是专家,它的驾驶我疯了。
I've tried to escape them using various methods: \", \\", \\\", "", \"" '"', \'"\', ... ...
As you can see from my 'try it all' approach I am no expert and it's driving me mad.
任何帮助将大大AP preciated。
Any help would be greatly appreciated.
Charlie101
Charlie101
推荐答案
相反字符串中的无功储存指令更好地在这里使用BASH数组:
Instead of storing command in a string var better to use BASH array here:
cmd=(psql ${DB_NAME} -F , -t --no-align -c "${SQL}" -o "${EXPORT_FILE}")
PSQL_RETURN=$( "${cmd[@]}" 2>&1 )
这篇关于一个子shell执行通话过程中的一个变量举行字符串麻烦转义引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!