Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building command strings using variables with various quote levels and spaces

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 quoting 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 form as the others, e.g., -H "X-Caption: Test Caption"

The problem is when run, it interprets the assignment as a command to be executed:

$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've tried resetting IFS before the code, but it didn't make a difference.

like image 805
jetset Avatar asked Dec 02 '25 05:12

jetset


2 Answers

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"
like image 171
Dennis Williamson Avatar answered Dec 03 '25 22:12

Dennis Williamson


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.

like image 38
tripleee Avatar answered Dec 03 '25 22:12

tripleee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!