Embed "cat file" in CURL data

I would like to cat the contents of a file.txt and use this as part of the --data field in my curl query.

I tried:

curl ... --data '{ "file_content":[" $(cat file.txt) ", ...]}"' ...

but that passes the string $(cat file.txt) to the server rather than interpreting it before sending.

I also tried:

curl ... --data '{ "file_content":[" `cat file.txt` ", ...]}"' ...

Again, the passes the string as it is instead of interpreting it.

Asked By: Juicy

||

You probably wouldn’t need 3 of those backslashes if you can remove the shell from the equation. Luckily, you can:

{   printf '{ "file_content":["'
    cat file.txt
    printf '", ...]}"'
}|  curl ... --data-binary @-          

Look at man curl. I suggest paying close attention to the differences between --data-ascii (which is what -d means), --data-binary, and --data-urlencoded.

Answered By: mikeserv
curl -d "$(cat /path/to/my/file.txt)" -X POST http://<your_base_URL>/api/v1/endpoint

Tested this one and it works. If you want to put everything against the file_content key, you have to be careful with the quoting, as the file you cat may have any number of quotes inside it.

Answered By: George Smith
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.