I want to create a bash script that reads a "payload" of binary data from an external file and spit out another bash script with this data escaped and encapsulated inside a string variable. Example:
- mydata.bin - The source data: a binary data file to be encapsulated
- myencoder.sh - The main perpetrator: a bash script that converts the binary data to a script with string variable
- mypayload.sh - The end result: a bash script generated by myencoder.sh that contains the encoded data as a string variable.
To use this I would run myscript.sh mydata.bin mypayload.sh
and myscript.sh would convert/escape/wrap/whatever the mydata.bin file into mypayload.sh
After running this command, the mypayload.sh
file would look something like this:
# Generated by myencoder.sh with data from mydata.bin
encoded_data="[...]ugly escaped string representation of the binary data found in mydata.bin[...]"
The problem I am facing that I amunsure how to solve is how the data would be properly encoded. I read that printf "%q" could be used to escape strings, but how to invoke it on data fetched from an external binary file eluded me completely.
So please, any stabs at this and any tips are welcome!
PS: I don't want to introduce any dependencies outside of bash if possible. Depending on bash 4.x features is OK.
PPS: The encoding should favour small size and encoding/decoding performance.