Snippet of Code # 4 – Embedding binary in a shell script

Sometimes it would be nice to embed a binary in a shell script, if only to provide a neat deployment for a command line tool.  There’s a right way to do this, so that the shell script remains editable even after the binary has been attached to it, and a wrong way – where the shell script is no longer editable at the end.  I’ll show you the right way here, and you can work out the wrong way yourself.

The first thing to do is prepare your binary so that it’s in the correct format for attaching to a shell script.  You can do this by base64 encoding it.  Given that you’re familiar with the command line (and if you aren’t, then you probably aren’t interested in this post either!), we’ll use the base64 utility rather than my graphical Convert64 tool.

base64 mybinary -o mybinary.b64

This done, you will have a text file called mybinary.b64.  Now we just need to add it to a shell script.

Using your favourite text editor, create a shell script containing the following lines:

echo x - mybinary.b64
sed 's/^X//' >mybinary.b64 << 'END-of-mybinary.b64'

Now paste the contents of mybinary.b64 onto the last line of the shell script.  Add the following lines after the base 64 encoded binary that you just pasted into the text editor:

END-of-mybinary.b64
base64 -D mybinary.b64 -o mybinary

exit

Add whatever other installation instructions that you need to execute between the ‘base64’ and the ‘exit’ and Bob’s your Uncle.  A binary file embedded into a shell script – as in this example (which won’t produce anything meaningful since the base64 is just nonsense):

echo x - demo.b64
sed 's/^X//' >demo.b64 << 'END-of-demo.b64'
XJVBERi0xLjMKJcTl8u.....................JUVPRgo=
END-of-demo.b64
base64 -D demo.b64 -o demo.pdf
exit

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.