Bash – How to handle raw binary data in a bash pipe

bashbinaryshell

I have a bash function that takes a file as a parameter, verifies the file exists, then writes anything coming off stdin to the file. The naive solution works fine for text, but I am having problems with arbitrary binary data.

echo -n '' >| "$file" #Truncate the file
while read lines
do  # Is there a better way to do this? I would like one...
    echo $lines >> "$file"
done

Best Answer

Your way is adding line breaks to every thing that it write in space of whatever separator ($IFS) is using to split up the read. Instead of breaking it up into newlines just take the whole thing and pass it along. You can reduce the entire bit of code above to this:

 cat - > $file

You don't need the truncate bit, this will truncate and write the whole STDIN stream out to it.

Edit: If you are using zsh you can just use > $file in place of the cat. You are redirecting to a file and truncating it, but if there is anything hanging out there waiting for something to accept STDIN it will get read at that point. I think you can do something like this with bash but you would have to set some special mode.

Related Question