作为一个单独的工具,它工作得很好:

curl "someURL"
curl -o - "someURL"

但这在流水线上行不通:

curl "someURL" | tr -d '\n'
curl -o - "someURL" | tr -d '\n'

它返回:

(23) Failed writing body

管道cURL输出的问题是什么?如何缓冲整个cURL输出,然后处理它?


当前回答

在Bash和zsh(也许还有其他shell)中,您可以使用进程替换(Bash/zsh)动态地创建一个文件,然后将该文件作为管道链中下一个进程的输入。

例如,我试图用jq和更少的方法从cURL解析JSON输出,但得到了失败的写入正文错误。

# Note: this does NOT work
curl https://gitlab.com/api/v4/projects/ | jq | less

当我用过程替换重写它时,它起作用了!

# this works!
jq "" <(curl https://gitlab.com/api/v4/projects/) | less

注意:jq使用它的第二个参数指定一个输入文件

额外的好处:如果你像我一样使用jq,并且想让彩色输出更少,可以使用下面的命令行:

jq -C "" <(curl https://gitlab.com/api/v4/projects/) | less -r

(感谢Kowaru解释了为什么会出现失败的写作体。然而,他们使用两次战术的解决方案对我不起作用。我还想找到一种解决方案,可以更好地扩展大文件,并尽量避免注释中提到的其他问题。)

其他回答

在我的情况下,服务器耗尽了磁盘空间。

用df -k检查它。

当我尝试两次通过tac进行管道处理时,我被提醒磁盘空间不足,如另一个答案:https://stackoverflow.com/a/28879552/336694中所描述的那样。它向我显示了错误消息写错误:设备上没有剩余空间。

所以这是编码的问题。Iconv解决了这个问题

curl 'http://www.multitran.ru/c/m.exe?CL=1&s=hello&l1=1' | iconv -f windows-1251 | tr -dc '[:print:]' | ...

因为我自己的打字错误,我也有同样的问题:

# fails because of reasons mentioned above
curl -I -fail https://www.google.com | echo $? 
curl: (23) Failed writing body

# success
curl -I -fail https://www.google.com || echo $?

我在做的时候也遇到了同样的问题:

curl - l https://packagecloud.io/golang-migrate/migrate/gpgkey | apt-key add -

上面的查询需要使用根权限执行。

用下面的方法解决了这个问题:

curl - l https://packagecloud.io/golang-migrate/migrate/gpgkey | sudo apt-key add -

如果在curl之前编写sudo,则会得到Failed writing body错误。

你可以这样做,而不是使用-o选项:

Curl [url] >[文件]