I'm having trouble with what I thought would be a very basic script, but has turned out to be more complicated than I imagined. I want to read data from STDIN and then write the data out to a file.
After much mucking about, I have a script which kindof works; it seems to work fine for text files (at least the MD5 sums match) but creates an unparseable file if you try it with a JPEG image.
# Start with a clean slate
rm file1
# http://unix.stackexchange.com/q/194388/5769
IFS=
#while read -r -N 8192 data; do
while read -r -N 40 data; do # Reduced bytesize for debugging
echo -n "$data" >> file1
done;
# Some data still remains because of how 'read' uses exit codes
echo -n "$data" >> file1
And the usage*:
$ curl -s "http://loripsum.net/api/plaintext/5/" | ./save.sh # Sucess
$ curl -s "http://lorempixel.com/400/200/food/" | ./save.sh # Failure: No error messages, but the file can't be opened with an image viewer
What's wrong with my code, and why doesn't it work for binary files?
* Yes, in this example, I could just use >
to redirect the data directly to a file, but I'm eventually using this code to save POST data from an HTTP form coming in from busybox's httpd
through STDIN.