Created
October 13, 2013 05:29
-
-
Save eyecatchup/6958497 to your computer and use it in GitHub Desktop.
Bash script to "pretty-print" minified CSS.
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
#!/bin/bash | |
#Author: Stephan Schmitz, https://github.com/eyecatchup, <[email protected]> | |
#Based on work by: Michael Bianco, http://developer.mabwebdesign.com/, <[email protected]> | |
#Description: Bash script to create a pretty-printed version of a minified CSS file. | |
# Note: Requires GNU sed. See: http://www.gnu.org/software/sed//sed.html | |
#Usage: prettyCss.sh inputfile [outputfile] | |
# If [outputfile] is not given, pretty-printed CSS will be send to stdout. | |
SED_COMMAND=/bin/sed # NOTE: Change the SED_COMMAND variable value to the path to your GNU sed! | |
# Helper function | |
doIt () { | |
echo "Saving formatted version of CSS file '$1' to '$2'." | |
exec 1>"$2" | |
} | |
# Check correct number of arguments | |
if [ $# -ne 1 ] && [ $# -ne 2 ]; then | |
echo "This script must be run with at least one argument, providing" | |
echo "the path to the minified css file to be pretty-printed." | |
echo "An optional second argument may be given, specifying the path" | |
echo "to the file to save the pretty-printed CSS to." | |
exit 1 | |
fi | |
# Check if argument points to a regular file. | |
if [ ! -f "$1" ]; then | |
echo "No regular file '$2' found! Typo?" | |
exit 1 | |
fi | |
# Check if the input file is readable. | |
if [ ! -r "$1" ]; then | |
echo "'$2' is not readable?!" | |
exit 1 | |
fi | |
# If output file already exists, ask for confirmation before overwriting it. | |
if [ -w "$2" ]; then | |
read -p "Overwrite existing '$2'? Type [y]es or [n]o ..." -n 1 -r | |
echo | |
if [[ $REPLY == "y" ]]; then | |
doIt $1 $2 | |
else | |
echo "Aborted. Please run the script again, using another output file name." | |
exit 2 | |
fi | |
elif [ ! -z "$2" ]; then | |
doIt $1 $2 | |
fi | |
# Some regex sugar | |
cat "$1" | | |
"$SED_COMMAND" 's/\([;{]\)\([^\n]\)/\1\n\t\2/g' | #do main formatting for all CSS properties and the beginning of CSS declerations | |
"$SED_COMMAND" 's/\([^}]\)}/\1;\n}\n\n/g' | #end of decleration formatting | |
"$SED_COMMAND" 's/{/ {/g' | #more beggining of CSS decleration | |
"$SED_COMMAND" 's/[,]/& /g' | #add some spaces for readability | |
"$SED_COMMAND" ' | |
/}/ { | |
N | |
N | |
s/}\n\([^\n]\)/}\n\n\1/ | |
}' #make sure there are two \n's after the closing brace | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is wonderful! thank you!