Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script containing binary executable

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!

like image 836
Katarzyna Gola Avatar asked Aug 23 '13 19:08

Katarzyna Gola


People also ask

What is $@ in bash script?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

What does $() mean in bash?

Example of command substitution using $() in Linux: Again, $() is a command substitution which means that it “reassigns the output of a command or even multiple commands; it literally plugs the command output into another context” (Source).


2 Answers

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.

like image 65
jlliagre Avatar answered Nov 01 '22 04:11

jlliagre


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

like image 10
Zoltán Haindrich Avatar answered Nov 01 '22 04:11

Zoltán Haindrich