-
-
Save RandyMcMillan/b4858efada0d267b228e2d016093f673 to your computer and use it in GitHub Desktop.
Embed TAR file in a shell script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env bash | |
| # Instructions: | |
| # 1) Create your TAR archive | |
| # tar -czpf file.tar <file1> <file2> ... <fileN> | |
| # 2) Append the TAR file contents to the script | |
| # cat file.tar >> embeddedPayload.sh | |
| # 3) Run script. (./embeddedPayload.sh) | |
| SCRIPT_PATH="${BASH_SOURCE[0]:-$0}" | |
| echo "Bash Source: ${SCRIPT_PATH}" | |
| # Script Varibles | |
| SCRIPT_DIR="$(cd -P "$(dirname "$SCRIPT_PATH")" && pwd)" | |
| MARKER_PREFIX="__TARFILE_" | |
| MARKER_SUFFIX="FOLLOWS__" | |
| PAYLOAD_MARKER="${MARKER_PREFIX}${MARKER_SUFFIX}" | |
| PAYLOAD_SIZE="$( | |
| PAYLOAD_MARKER="$PAYLOAD_MARKER" \ | |
| perl -0777ne ' | |
| my $marker = $ENV{PAYLOAD_MARKER} // exit 1; | |
| my $offset = rindex($_, $marker); | |
| exit 1 if $offset < 0; | |
| my $payload = substr($_, $offset + length($marker)); | |
| exit 1 if length($payload) < 3 || substr($payload, 0, 3) ne "\x1f\x8b\x08"; | |
| print length($payload); | |
| ' "$SCRIPT_PATH" | |
| )" | |
| echo "Script Dir: ${SCRIPT_DIR}" | |
| echo "Payload Size: ${PAYLOAD_SIZE}" | |
| # Extract | |
| echo "Extracting install ... " | |
| cd "$SCRIPT_DIR" || exit 1 | |
| if [ "${PAYLOAD_SIZE:-0}" -le 0 ]; then | |
| echo "No embedded payload found. Append a tar.gz archive to ${SCRIPT_PATH##*/} first." >&2 | |
| exit 1 | |
| fi | |
| PAYLOAD_MARKER="$PAYLOAD_MARKER" \ | |
| perl -0777ne ' | |
| BEGIN { binmode STDOUT; } | |
| my $marker = $ENV{PAYLOAD_MARKER} // exit 1; | |
| my $offset = rindex($_, $marker); | |
| exit 1 if $offset < 0; | |
| print substr($_, $offset + length($marker)); | |
| ' "$SCRIPT_PATH" | tar -xzpvf - | |
| exit 0 | |
| # NOTE: Don't place any newline characters after the last line below. | |
| __TARFILE_FOLLOWS__ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment