Way to embed an executable binary in a shell script without extra tools

binaryexecutablescripting

I'm looking for a way to have an executable binary hardwired into a script. Something like this:

#!/bin/bash
...some shell code
execute binary:
    >>>
        binary
        code
        ...
    <<<
...some more shell code possibly

I've found this solution, which uses uuencode and is good. But it depends on shrutils, which seem to be an extra, as they're not included by default on my Debian.

I've been thinking of having the binary encoded with base64 and then decoding it and somehow executing, possibly without creating any temp files. I remember there was a library that's responsible for executing things, but forgot what it was.

It might be the best to have a construct as simple as this execute:

$ <(base64 out | base64 -d)
bash: /dev/fd/63: Permission denied

Best Answer

How about:

unpack() {
    tail +9 "$0" > /tmp/xxx.$$
    chmod +x /tmp/xxx.$$
}
unpack
/tmp/xxx.$$ <add args here>
rm /tmp/xxx.$$
exit
<add the binary here>

If you don't like to have binary data in the script, you may encode it and replace cat by the related decoder.

Note that you need to replace the +9 by the line number where the binary starts in case that you modify the script to be of different length.

If your tail implementation does not support the argument +9, try -n +9 instead.

If you are in fear of clobbering an existing /tmp file, try to use mktemp(1) to create the tmp filename.

Note that this method was used by the upgrade scripts for the SunPro compiler suite that included the compressed tar archive with the whole upgrade and some shell code to manage the handling around that.

Related Question