Skip to content

Instantly share code, notes, and snippets.

@eyecatchup
Created October 13, 2013 05:29
Show Gist options
  • Save eyecatchup/6958497 to your computer and use it in GitHub Desktop.
Save eyecatchup/6958497 to your computer and use it in GitHub Desktop.
Bash script to "pretty-print" minified CSS.
#!/bin/bash
#Author: Stephan Schmitz, https://github.com/eyecatchup, <eyecatchup@gmail.com>
#Based on work by: Michael Bianco, http://developer.mabwebdesign.com/, <software@mabwebdesign.com>
#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
@mikemowgli
Copy link

This is wonderful! thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment