Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ssh60/11835400ced292814f2f40d59c7372bb to your computer and use it in GitHub Desktop.
Save ssh60/11835400ced292814f2f40d59c7372bb to your computer and use it in GitHub Desktop.
Quick bash script to create self-extracting .sh files /w Base64 encoded contents (e.g. binary, zip, etc)
#!/bin/bash
#
# create_self_extracting_script.sh <INPUT_FILE> [<OUTPUT_SCRIPT>]
#
# Creates a self-extracting shell script containing INPUT_FILE as Base64-encoded
# bytes. When executed, the script writes INPUT_FILE and restores its permissions.
#
# (c) Jeff Ward, 2017
# MIT License
FILENAME=$1
SCRIPT=${2:-extract.sh}
if [[ $# -eq 0 ]] ; then
echo "Usage: $0 INPUT_FILE [OUTPUT_SCRIPT]"
exit 0
fi
if [ ! -f "$FILENAME" ]; then
echo "File not found: $FILENAME"
exit 1
fi
echo "Writing $SCRIPT"
# Capture current permissions
PERMS="644"
if [[ "$OSTYPE" == "linux-gnu" ]]; then
PERMS=`stat -c "%a" "$FILENAME"`
elif [[ "$OSTYPE" == "darwin"* ]]; then
PERMS=`stat -f "%A" "$FILENAME"`
fi
cat > "$SCRIPT" << EOF
FILENAME="$FILENAME"
# Extract the .zip file
LINES=\`awk '/^__BASE64_ARCHIVE__/ {print NR + 1; exit 0; }' "\$0"\`
tail -n+\$LINES "\$0" | base64 --decode > "\$FILENAME" || { echo "Failed to write \$FILENAME" ; exit 1; }
# Restore permissions
chmod $PERMS "\$FILENAME"
echo "Extracted ./\$FILENAME"
exit 0
__BASE64_ARCHIVE__
EOF
base64 "$FILENAME" >> "$SCRIPT"
chmod a+x "$SCRIPT"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment