use pipe for curl data

2020-02-17 09:04发布

I'm trying to pass the cat output to curl:

$ cat file | curl --data '{"title":"mytitle","input":"-"}' http://api

But input is literally a -.

标签: curl pipe
8条回答
地球回转人心会变
2楼-- · 2020-02-17 09:11

You can use the magical stdin file /dev/stdin

cat data.json | curl -H "Content-Type: application/json" -X POST -d "$(</dev/stdin)" http://api
查看更多
何必那么认真
3楼-- · 2020-02-17 09:11
# Create the input file
echo -n 'Try                                                                     
查看更多
放荡不羁爱自由
4楼-- · 2020-02-17 09:13

I spent a while trying to figure this out and got it working with the following:

cat data.json | curl -H "Content-Type: application/json" -X POST -d @- http://api
查看更多
Anthone
5楼-- · 2020-02-17 09:14

Curl documentation for -d option

If you start the data with the letter @, the rest should be a file name to read the data from, or - if you want curl to read the data from stdin. Multiple files can also be specified. Posting data from a file named 'foobar' would thus be done with -d, --data @foobar. When --data is told to read from a file like that, carriage returns and newlines will be stripped out. If you don't want the @ character to have a special interpretation use --data-raw instead.

Depending of your HTTP endpoint, server configuration, you should be good by using this format:

curl -d @data.json http://api

查看更多
SAY GOODBYE
6楼-- · 2020-02-17 09:14

Sounds like you want to wrap the content of input in a JSON body, and then have that sent over with a POST request. I think that the simplest way to do that is to manipulate stdin first and then push that over to curl using -d @-. One way could look like this:

cat <(echo '{"title":"mytitle","input":"') file <(echo '"}') \
| curl -d @- http://api

I'm using <(echo) to use cat to merge strings and files, but there is almost certainly a better way.

Keep in mind that this does not escape the contents of file and that you may run into issues because of that.

查看更多
啃猪蹄的小仙女
7楼-- · 2020-02-17 09:21

Try

curl --data '{"title":"mytitle","input":"'$(cat file)'-"}' http://api
查看更多
登录 后发表回答