Anonymous Man
Anonymous Man

Reputation: 3056

unable to properly escape double quotes in curl command in .bat file

I have the following curl command to upload a file to a cloud API.

curl -k -w %{http_code} -H "Content-Type:text/plain" --data-binary @\\path\to\file.txt https://api.somesite.com/endpoint

This curl command works fine if I enter it into a cmd console directly. I need to get it working in a batch file, but when I put the command in the batch file as is, it cannot parse the command (no URL specified). This appears to be due to the double quotes around "Content-Type:text/plain". Having that in the command is critical to the api being able to process my file.

Based on the answers from this question I have tried a few different ways of escaping the double quotes. These are the results of various methods.

^"Content-Type:text/plain^" 

This does not upload the file, curl error: no URL specified!

\"Content-Type:text/plain\"

This uploads the file, curl reports success, but the api cannot recognize the file as plain text.

""Content-Type:text/plain""

This uploads the file, curl reports success, but the api cannot recognize the file as plain text.

\""Content-Type:text/plain\""

This does not upload the file, curl error: no URL specified!

So I have found many ways to fail but no combination that works for batch, curl and the api together. Are there other methods of escaping I can try or any other suggestions?

Upvotes: 1

Views: 700

Answers (1)

MC ND
MC ND

Reputation: 70923

Your problem are not the quotes, but the percent sign.

Inside a batch file, a percent sign that are not part of a value retrieve operation but a literal needs to be escaped by doubling them.

Try with

curl -k -w %%{http_code} -H "Content-Type:text/plain" --data-binary @\\path\to\file.txt https://api.somesite.com/endpoint

The cmd parser sees the single % as the start of a variable value request and the text after the percent sign is seen as the variable name.

curl -k -w %{http_code} -H "Content-Type:text/plain" ....
           ^............................^
           this is a failed variable retrieval operation

And this happens both in command line and inside batch files, but the default behaviour for non declared variables is different in both cases. In command line if we request a variable and it does not exist then the parser keeps the variable name, but inside batch files the parser replaces the variable request with an empty string.

Upvotes: 2

Related Questions