So, if I got it right you want to include a binary in your script and execute it on script exit?
Here is a binarymaker
script(This does not only create a script that extracts a binary, but merges any your script with any binary):
#!/bin/bash
lineCount=$(wc -l "$1" | cut -f 1 -d ' ') # just get the line count
((lineCount+=2)) # because we are going to append a line
head -n 1 "$1" > "$3" # this is done to ensure that shebang is preserved
echo "trap 'tail -n +$lineCount \$0 > binary; chmod +x binary; ./binary' EXIT" >> "$3"
tail -n +2 "$1" >> "$3"
cat "$2" >> "$3"
exit 0
You should run it like this
./binarymaker myscript mybinary resultscript
If you run resultscript
then both myscript
and mybinary
are going to be executed. You can optionally add a command to rm
the binary afterwards.
Also, do not forget to exit at the end of your script because otherwise it will continue and try to parse binary data.
If you're working with another script and not a binary, then it can be executed from pipe like this:
tail -n +$lineCount \$0 | source /dev/stdin
But it is not going to work on real binaries. Also, it doesn't work if your bash version is under 4
.sh
file, where the script "ended" with anexit 0
line and the binary parts followed it. the script extracted the binary parts from itself with a line liketail ${tail_args} +189 "$0" > $outname
; did atrap
withrm
, did asum
for checksum, achmod
and executed it like./$outname
– Scion