Command line string using variables with different levels and quotation spaces

I have a script that works curl. I want to be able to optionally add a parameter -Hif the row is not empty. What complex are citation levels and spaces.

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

The idea is that the CAPT variable is either empty or contains the desired -H header in the same way as others, for example, -H "X-Caption: Test Caption"

The problem is that at startup it interprets the assignment as a command to execute:

$bash -x -v test.sh
+ '[' 'Test caption' '!=' '' ']'
+ CAPT=-H
+ 'X-Caption: Test caption'
./test.sh: line 273: X-Caption: Test caption: command not found

I tried to reset the IFS before the code, but that did not affect.

+3
source share
3 answers

The key to doing this work is using 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"
+8
source

, , , .

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" ...

, ${var-value} value, var .

+2

- . curl, -H , -H ( ) . eval, .

, TICK.

:

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
-1

All Articles