webSIGHTdesigns - Web Design, Web Development, Web Hosting

Bash Script to Run YUI Compressor in Linux

Posted on Monday, November 4th, 2013 at 9:34 pm
by webSIGHTdesigns

This Bash script will allow you to easily minify your JS and CSS files from the command line.

Compressing, or minifying, your JS and CSS is an important task for web developers. The Online YUI Compressor is a great tool and easy way of quickly using the YUI Compressor, but if you download the YUI Compressor jar file and put it somewhere on your own Linux system, you can use the following Bash script to easily minify JS and CSS files from the command line.

To use the YUI Compressor, you download the jar file and then run a command like:

$ java -jar /path/to/yuicompressor-2.4.8.jar /path/to/script.js -o /path/to/script.min.js 

To simplify things a bit, this simple bash script will give you a new "min" command. Create a file at /usr/local/bin/min:


# min command
# version 0.1 beta by @websightdesigns


if [ "$1" != '' ]; then
  EXT=`echo "$1" | awk -F . '{print $NF}'`
  if [ "$EXT" = 'js' ] || [ "$EXT" = 'css' ]; then
    if [ "$2" = '' ]; then
    elif [ "$2" != '' ]; then
    /usr/bin/java -jar $YUICOMPRESSOR $1 -o $MINFILE --charset utf-8 -v
    USR=$( ls -l $1 | awk '{ print $3 }' )
    GRP=$( ls -l $1 | awk '{ print $4 }' )
    chown $USR:$GRP $MINFILE
elif [ "$1" = 'help' ] || [ "$1" = '' ]; then
  echo "min 0.1 beta"
  echo "description: uses the YUI Compressor to compress (minify) js and css files."
  echo ""
  echo "usage:"
  echo "sudo min <uncompressed filename> <compressed filename>"
  echo "sudo min <uncompressed filename>"
  echo "example: to minify the file script.js just run the command 'sudo min script.js'"
  echo "filename of <uncompressed filename> must end in \".js\" or \".css\""
  echo "if <compressed filename> is not specified then \".min\" will be placed before the file extension"
  echo ""

# eof

Save the above Bash script to the /usr/local/bin/min file and then make the file executable:

$ sudo chmod +x /usr/local/bin/min

Now you can use the command sudo min script.js to compress a file script.js in the current directory, and save it to a file named script.min.js. If you prefer the output files be saved to file names like script-min.js just change the MIN variable to "-min".

Please Sign In

Please sign in to post a comment.

Web Development

View details »

Web Hosting

View details »

Our Portfolio

View portfolio »

WebSight Designs webSIGHTdesigns preferred email webSIGHTdesigns United States United States