Minification and Obfuscation of a shell script are two different things.
Minification means reducing the size of a script by removing all unnecessary characters from source code without changing its functionality. Obfuscation on the other hand means making the script difficult, if not impossible, to read.
Minification:
To minify a big script, you can run the following code against the actual script you want to minify:
#!/bin/sh
Script=${1}
if [ ! -z "${Script}" ] && [ -f ${Script} ] ; then
CurrenTime=$(date | sed -e 's~ ~_~g' -e 's~:~~g')
cp ${Script} ${Script}_${CurrenTime}
#### Remove all empty lines
#### Remove lines that begin with spaces and a comment sign #
#### Remove all comment lines (meaning, lines that begin with a "#")
awk '
(/.*/ || /#!/) && (!/^#$/) &&
(!/^#[[:blank:]]/) && (!/^#[a-z]/) &&
(!/^#[A-Z]/) && (!/^##/) &&
(!/^\t#/) && (!/^[[:space:]]*$/) &&
( /^#.*!/ || !/^[[:space:]]*#/)
' ${Script} | sed 's_^[[:space:]]*__g' > ${Script}.tmp 2>/dev/null
#' ${Script} > ${Script}.tmp 2>/dev/null (comment out the above line and uncomment this line if your HEREDOCS are affected)
ExitCode=$?
if [ ${ExitCode} -eq 0 ] && [ -s ${Script}.tmp ] ; then
echo
echo "SUCCESS: Your newly [ minified ] script can be found here [ ${Script}.tmp ]."
echo "Review the script [ ${Script}.tmp ] and if happy with it, replace your original script with it!"
echo "NOTE: Your original script [ ${Script} ] was backed up as [ ${Script}_${CurrenTime} ]!"
echo
exit 0
else
echo
echo "FAILURE: Unable to [ minify ] the specified script [ ${Script} ]!!!"
echo
exit 2
fi
else
echo
echo "USAGE: ${0} <your-script>"
echo
exit 3
fi
Note, minification tends to make a difference only if the script being minified is big...with several hundred or even thousands of lines. I was able to trim off a few Megabytes from a script using the above code.
Obfuscation:
After the above minification is completed, you can just stop right there if size reduction is what you're going for. If however, after the minification, you also wish to obfuscate your script as well, you have options.
The simplest way to obfuscate your script is through the use of encryption tools such as as Openssl.
To encrypt your script using Openssl:
1. cat <your-script> | openssl aes-128-cbc -a -salt -k "specify-a-password" > yourscript.enc
OR
2. openssl aes-128-cbc -a-salt -in <path-to-your-script> -k "yourpassword"
To decrypt a script using Openssl (notice the '-d'):
1. cat yourscript.enc | openssl aes-128-cbc -a -d -salt -k "specify-a-password" > yourscript.dec
OR
2. openssl aes-128-cbc -a -d -salt -in <path-to-your-script> -k "yourpassword" > yourscript.dec
Encryption/Obfuscation:
- If your ultimate goal is to make it difficult to others to read your script, try pasting it here to have an encrypted copy generated for you.
- In case you change your mind about SHC, the latest version can be downloaded here.