How to Minify CSS using simple bash commands

Minify CSS or JS file is very important task in Web development for optimized performance. In theory the term magnification or compression in the context of CSS/JS means removing all unnecessary characters, such as spaces, new lines, comments without affecting the functionality of the source code.

If you goggle out, there are plenty of tools and scripts that will help you in accomplishing this task, but most of time these tools depend on heavy weight language for framework (Java, npm, etc..). I don’t want to install and setup those heavy weight stuffs to accomplish simple task.

Here is the script I have came up with

cat input_file.css | \
sed -r ':a; s%(.*)/\*.*\*/%\1%; ta; /\/\*/ !b; N; ba' \
| tr -d '\t' | tr -d ' ' | tr -d '\n' | tr -s ' ' ' ' > output_file.min.css

Explanation: What does the commands do

  • sed command removes the block css comments
  • tr -d ‘\t’ – Removes tab
  • tr -d ‘ ‘ – Removes spaces
  • tr -d ‘\n’ – Removes new line
  • tr -s ‘ ‘ ‘ ‘ – Removes multiple spaces

I have tested the command on bootstrap source, I got almost near to the size of bootstrap.min.css

cat bootstrap.css | \
sed -r ':a; s%(.*)/\*.*\*/%\1%; ta; /\/\*/ !b; N; ba' \
| tr -d '\t' | tr -d ' ' | tr -d '\n' | tr -s ' ' ' ' > bootstrap.mohamed.min.css

Also the commands ran pretty fast,

real 0m0.054s
user 0m0.054s
sys 0m0.013s

Here is the file size comparison

$ ls -l
-rw-r--r-- 1 mohamed mohamed 146082 Nov 24 2015 bootstrap.css
-rw-r--r-- 1 mohamed mohamed 121260 Nov 24 2015 bootstrap.min.css
-rw-rw-r-- 1 mohamed mohamed 121149 Jul 19 20:22 bootstrap.mohamed.min.css

I am happy with this script, hence sharing in a hope that it will be help full to some one..