Bash script containing binary executable

Katarzyna Gola picture Katarzyna Gola · Aug 23, 2013 · Viewed 16.8k times · Source

Is it possible to write a bash script, which would contain a binary executable program inside?

I mean a script, which would contain a dump of an executable in a textual form, which will be dumped back to an executable by this script when it is executed?

I would love to know a solution, which will work out of the box without a need of installing additional packages. Is it possible?

Thanks!

Answer

Zoltán Haindrich picture Zoltán Haindrich · Aug 23, 2013

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...