Bash script containing binary executable

I tried this out and it works. Hex was generated with xxd.

#!/bin/bash

xxd -r >foo <<'EndHere'
0000000: 7f45 4c46 0201 0100 0000 0000 0000 0000  .ELF............
0000010: 0200 3e00 0100 0000 e003 4000 0000 0000  ..>.......@.....
0000020: 4000 0000 0000 0000 000a 0000 0000 0000  @...............
0000030: 0000 0000 4000 3800 0800 4000 1e00 1b00  [email protected]...@.....
0000040: 0600 0000 0500 0000 4000 0000 0000 0000  ........@.......
0000050: 4000 4000 0000 0000 4000 4000 0000 0000  @.@.....@.@.....
...
0001960: 6400 5f65 6461 7461 006d 6169 6e00 5f69  d._edata.main._i
0001970: 6e69 7400                                nit.
EndHere
chmod +x foo
./foo

Don't reinvent the wheel like several other answers are suggesting, just use the venerable shar command which is precisely doing this by design.

Assuming the file you want to embed in your script is binaryfile, simply run

$ shar binaryfile > binaryfile.shar

and you are set. You have a shell script named binaryfile.shar which when executed will extract binaryfile.


i never done something like this before ;) this will compile some c source, create a b.bash script containing the binary (and the original script for simple development)

(a.bash)

#!/bin/bash

if [ "$0" == "b.bash" ];then
  tail -n +$[ `grep -n '^BINARY' $0|cut -d ':' -f 1` + 1 ] $0 | base64 -d > a2.out
  chmod +x a2.out
  ./a2.out
  echo $?
  exit
fi

cat "$0" > b.bash
echo "BINARY" >> b.bash
cat > a.c << EOF
int     main(){
        return 12;
}
EOF
gcc a.c 
base64 a.out >> b.bash

invoke with (a.bash generates b.bash):

bash a.bash ;bash b.bash

i don't know how to evade writing out the binary into a temporary file before execution...