use pipe for curl data

后端 未结 8 405
盖世英雄少女心
盖世英雄少女心 2020-12-23 13:26

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

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

Bu

相关标签:
8条回答
  • 2020-12-23 13:56
    # Create the input file
    echo -n 'Try                                                                     
    0 讨论(0)
  • 2020-12-23 13:59

    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
    
    0 讨论(0)
  • 2020-12-23 14:03

    If you want to type/paste the data without escaping or polluting your bash history then, you can use this

    cat | curl -H 'Content-Type: application/json' http://api -d @-
    

    Which drops you into cat where you can input the data, directly, e.g. Shift + Insert in your terminal. You finish with a newline and a Ctrl + D which signals to cat that you're done. That data is then passed to curl, and you have a reusable history entry.

    0 讨论(0)
  • 2020-12-23 14:07

    Try

    curl --data '{"title":"mytitle","input":"'$(cat file)'-"}' http://api
    
    0 讨论(0)
  • 2020-12-23 14:11

    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 --data-binary @- http://api
    
    0 讨论(0)
  • 2020-12-23 14:13

    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.

    0 讨论(0)
提交回复
热议问题