Building command strings using variables with various quote levels and spaces

≡放荡痞女 提交于 2019-12-01 08:39:53
Dennis Williamson

The key to making this work is to use an array.

caption="Test Caption"

if [[ $caption ]]; then 
    CAPT=(-H "X-Caption: $caption")
fi

curl -A "$UA" -H "Content-MD5: $MD5" -H "X-SessionID: $SID" -H "X-Version: 1"  "${CAPT[@]}" "http://upload.example.com/$FN"

If you only need to know whether or not the caption is there, you can interpolate it when it needs to be there.

caption="Test Caption"
NOCAPT="yeah, sort of, that would be nice"

if [ "${caption}" != "" ]; then 
    unset NOCAPT
fi

curl ${NOCAPT--H "X-Caption: ${caption}"} -A "$UA" ...

To recap, the syntax ${var-value} produces value if var is unset.

I finally did get it to work. Part of the problem is specific to curl, in that when using the -H option to set custom headers, it seems to work best when everything after the -H (that is, both the custom header name and value) are protected by single quotes. Then, I needed to pass the constructed string through eval to get it to work.

To make this easier to read, I store a single quote in a variable named TICK.

Example:

TICK=\'
#
HDRS=""
HDRS+=" -H ${TICK}Content-MD5: ${MD5}${TICK}"
HDRS+=" -H ${TICK}X-SessionID: ${SID}${TICK}"
HDRS+=" -H ${TICK}X-Version: 1.1.1${TICK}"
HDRS+=" -H ${TICK}X-ResponseType: REST${TICK}"
HDRS+=" -H ${TICK}X-ID: ${ID}${TICK}"

if [ "${IPTC[1]}" != "" ]; then
    HDRS+=" -H ${TICK}X-Caption: ${IPTC[1]}${TICK}"
fi
if [ "${IPTC[2]}" != "" ]; then
    HDRS+=" -H ${TICK}X-Keywords: ${IPTC[2]}${TICK}"
fi

#
# Set curl flags
#
CURLFLAGS=""
CURLFLAGS+=" --cookie $COOKIES --cookie-jar $COOKIES"
CURLFLAGS+=" -A \"$UA\" -T ${TICK}${the_file}${TICK} "

eval curl $CURLFLAGS $HDRS -o $OUT http://upload.example.com/$FN
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!