Take the 2-minute tour ×

After I use the following command,

pngString="$(cat example.png)"    
echo -n "$pngString" > tmp.png

I can't open the tmp.png as a PNG file. Maybe some information is lost when I use $pngString to store the image file.

So the question is: How can I store the complete image information using a variable in bash script?

share|improve this question
The cat command works fine (to store the image data in the variable). Just remove the double quotes. The question is what you want to do with this data after saving them in the variable? –  coffeMug Dec 29 '13 at 10:03
cat and echo and all its ilk are at heart text utilities. Letting them loose unsuspectingly on binary files will have unpredictable results. That's why things like base64 were invented. –  Shadur Dec 29 '13 at 11:06
Why do you want to have it as a variable? Shell variables are typically intended to store small amount of text, not large amounts of binary data. None of the usual shell can cope with binary data in variables (they choke on null bytes) except zsh. –  Gilles Dec 29 '13 at 14:23

1 Answer 1

up vote 15 down vote accepted

You are right in that echo & company don't seem to handle binary that well. I suspect that the null characters break the stream all too early.

You can convert picture information in some ASCII based format. For instance, this is with base64:

$ pic=`base64 pic.jpeg`
$ echo $pic | base64 --decode > pic2.jpeg
$ diff pic*
$ echo $?
share|improve this answer
In my bash system I had to enclose the variable in quotes, probably because base64 can contain white space: echo "$pic" | base64 --decode > pic2.jpeg –  OldTimer Dec 31 '13 at 23:54

Your Answer


