Skip to content

Instantly share code, notes, and snippets.

@gromgit
Created August 2, 2024 07:54
Show Gist options
  • Save gromgit/7ac9e2fa3a31b620f616abffca0f06a5 to your computer and use it in GitHub Desktop.
Save gromgit/7ac9e2fa3a31b620f616abffca0f06a5 to your computer and use it in GitHub Desktop.
sharexec - create a shar that also runs a specific executable bundled in the shar
#!/usr/bin/env bash
# USAGE: sharexec [-d <dir>] <executable> <file>... > my.sh
# Creates a shar file containing <executable> + all <file>s
# On execution:
# 1. unpack everything in <dir> (default: temp dir)
# 2. run <executable>
# 3. if temp dir used, remove it
warn() {
echo "WARNING: $*" >&2
}
err() {
echo "ERROR: $*" >&2
}
fatal() {
echo "FATAL ERROR: $*" >&2
exit 1
}
dir=
while true; do
case "$1" in
-d) dir=$2; shift;;
*) break;;
esac
shift
done
# the shar generator
echo '#!/usr/bin/env bash'
declare -f warn err fatal
declare -p dir
cat <<EOS
if [[ -z \$dir ]]; then
dir=\$(mktemp -d /tmp/sharexec.XXXXXX) || fatal "Unable to create temp dir"
trap 'rm -fr "\$dir"' EXIT
fi
mkdir -p "\$dir" || fatal "Unable to create dir '\$dir'"
cd "\$dir" || fatal "Unable to cd into '\$dir'"
EOS
for i in "$@"; do
if [[ -r $i ]]; then
cat <<EOS
base64 -d >"$(basename "$i")" <<'EOF' || fatal "Unable to decode '$i'"
$(base64 < "$i")
EOF
EOS
[[ -s $bin ]] || bin=$(basename "$i")
else
warn "Unable to read '$i', skipping"
fi
done
cat <<EOS
chmod +rx "$bin"
./"$bin"
EOS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment