Building command strings using variables with various quote levels and spaces

前端 未结 3 2031
暗喜
暗喜 2021-01-14 07:34

I have a script that runs curl. I want to be able to optionally add a -H parameter, if a string isn\'t empty. What\'s complex is the levels of qu

3条回答
  •  情深已故
    2021-01-14 08:06

    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
    

提交回复
热议问题