Embed an Image Into A Shell Script

Instead of having to distribute an image file with a shell script that called for the file, an idea came to mind to embed the image into the shell script. Although one way was found, I devised an alternate simpler method to distribute the image file embedded in the script.

The first method uses four lines of code. This method was found on YouTube.

#!/bin/bash

ARCHIVE=$(awk '/^__ARCHIVE_BELOW__/{print NR + 1;exit;0;}' $0)
tail -n+$ARCHIVE $0 > image.jpg
exit
__ARCHIVE_BELOW__

To use the above code, you can embed the image into the file like this.

 cat myimage.jpg >> myscript.sh

Then execute the command to create your image.

./myscript.sh

However, for one reason or another, the code got corrupted each and every time when using WinSCP to access the Linux system. Out of frustration, I devised another method using the base64 command to create a file containing the image file as a base64 file.

base64 myimage.jpg > myimage.b64

From within the bash script, use echo to recreate the image. For the sake of demonstration, the code below has been greatly condensed to save space.

#!/bin/bash

echo '/9j/4AAQSkZJRgABAQEBLAEsAAD/4QCsRXhpZgAATU0AKgAAAAgACQEaAAUAAAABAAAAegEbAAUA
bnQuTkVUIHYzLjUuMTEAAAGGoAAAsY//2wBDAAEBAQEBAQEBAQEBAQECAgMCAgICAgQDAwIDBQQF
BQUEBAQFBgcGBQUHBgQEBgkGBwgICAgIBQYJCgkICgcICAj/2wBDAQEBAQICAgQCAgQIBQQFCAgI
AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAH/9k=' > mynewimage.b64
base64 -d mynewimage.b64 > mynewimage.jpg
rm -rf mynewimage.b64

Better way.

#!/bin/bash
echo '/9j/4AAQSkZJRgABAQEBLAEsAAD/4QCsRXhpZgAATU0AKgAAAAgACQEaAAUAAAABAAAAegEbAAUA
bnQuTkVUIHYzLjUuMTEAAAGGoAAAsY//2wBDAAEBAQEBAQEBAQEBAQECAgMCAgICAgQDAwIDBQQF
BQUEBAQFBgcGBQUHBgQEBgkGBwgICAgIBQYJCgkICgcICAj/2wBDAQEBAQICAgQCAgQIBQQFCAgI
AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAH/9k=' | base64 -d > mynewimage.jpg

After repeated effort using WinSCP, the code never got corrupt. Using the diff command revealed no change between the original jpg and the new jpg.