Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does cURL return error "(23) Failed writing body"?

This happens when a piped program (e.g. grep) closes the read pipe before the previous program is finished writing the whole page.

In curl "url" | grep -qs foo, as soon as grep has what it wants it will close the read stream from curl. cURL doesn't expect this and emits the "Failed writing body" error.

A workaround is to pipe the stream through an intermediary program that always reads the whole page before feeding it to the next program.

E.g.

curl "url" | tac | tac | grep -qs foo

tac is a simple Unix program that reads the entire input page and reverses the line order (hence we run it twice). Because it has to read the whole input to find the last line, it will not output anything to grep until cURL is finished. Grep will still close the read stream when it has what it's looking for, but it will only affect tac, which doesn't emit an error.


For completeness and future searches:

It's a matter of how cURL manages the buffer, the buffer disables the output stream with the -N option.

Example: curl -s -N "URL" | grep -q Welcome


Another possibility, if using the -o (output file) option - the destination directory does not exist.

eg. if you have -o /tmp/download/abc.txt and /tmp/download does not exist.

Hence, ensure any required directories are created/exist beforehand, use the --create-dirs option as well as -o if necessary


The server ran out of disk space, in my case.

Check for it with df -k .

I was alerted to the lack of disk space when I tried piping through tac twice, as described in one of the other answers: https://stackoverflow.com/a/28879552/336694. It showed me the error message write error: No space left on device.


You can do this instead of using -o option:

curl [url] > [file]


So it was a problem of encoding. Iconv solves the problem

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

I had the same error but from different reason. In my case I had (tmpfs) partition with only 1GB space and I was downloading big file which finally filled all memory on that partition and I got the same error as you.