Search code examples
bashcurlquotes

How to echo variables inside an ANSI quoted string


I need to execute a curl command like this:

#!/bin/bash

shopid=9932781
itemid=231873991
curl -sSb /tmp/cookies 'https://website.com' -H 'cookie: csrftoken=mytoken' -H 'x-csrftoken: mytoken' -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary' -H 'referer: https://website.com' \
  --data-binary $'------WebKitFormBoundary\r\nContent-Disposition: form-data; name="shopid"\r\n\r\n${shopid}\r\n------WebKitFormBoundary\r\nContent-Disposition: form-data; name="itemid"\r\n\r\n${itemid}\r\n------WebKitFormBoundary\r\nContent-Disposition: form-data; name="quantity"\r\n\r\n1\r\n------WebKitFormBoundary\r\nContent-Disposition: form-data; name="donot_add_quantity"\r\n\r\nfalse\r\n------WebKitFormBoundary\r\nContent-Disposition: form-data; name="update_checkout_only"\r\n\r\nfalse\r\n------WebKitFormBoundary\r\nContent-Disposition: form-data; name="source"\r\n\r\n\r\n------WebKitFormBoundary\r\nContent-Disposition: form-data; name="checkout"\r\n\r\ntrue\r\n------WebKitFormBoundary--\r\n'

The $'' quotes are necessary or else (ie. in the double-quoted case) \r\n won't work -- but with this form, $shopid and $item aren't replaced with their values.

How can I get both behaviors?


Solution

  • You need to make that code maintainable

    binary_data=$( cat <<END_DATA | sed 's/$/\r/'
    ------WebKitFormBoundary
    Content-Disposition: form-data; name="shopid"
    
    ${shopid}
    ------WebKitFormBoundary
    Content-Disposition: form-data; name="itemid"
    
    ${itemid}
    ------WebKitFormBoundary
    Content-Disposition: form-data; name="quantity"
    
    1
    ------WebKitFormBoundary
    Content-Disposition: form-data; name="donot_add_quantity"
    
    false
    ------WebKitFormBoundary
    Content-Disposition: form-data; name="update_checkout_only"
    
    false
    ------WebKitFormBoundary
    Content-Disposition: form-data; name="source"
    
    
    ------WebKitFormBoundary
    Content-Disposition: form-data; name="checkout"
    
    true
    ------WebKitFormBoundary--
    END_DATA
    )
    
    curl_opts=( 
        -sSb /tmp/cookies 
        -H 'cookie: csrftoken=mytoken' 
        -H 'x-csrftoken: mytoken' 
        -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary' 
        -H 'referer: https://website.com' 
        --data-binary "$binary_data"
    )
    
    curl "${curl_opts[@]}" 'https://website.com'