Skip to content

Instantly share code, notes, and snippets.

@mattgrande
Created October 10, 2013 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattgrande/6924734 to your computer and use it in GitHub Desktop.
Save mattgrande/6924734 to your computer and use it in GitHub Desktop.
Combine & Compress javascript files in order.
#!/bin/bash
# This method returns 1 if a string is contained in an array, and 0 if it is not.
containsElement () {
local e
# For each element in the second argument to this method
# The ${} indicates that this is an array, the @ indicates we want all
# elements, and the 2 denotes that this is the second argument to this
# method.
for e in "${@:2}"
do
# If the current element, $e, is equal to the first argument passed
# into this method, $1, return 1
[[ "$e" == "$1" ]] && return 1
done
# We'ver reached the end of the loop, return 0
return 0
}
# The directory your JavaScript files are in.
JS_DIR='js'
# A temporary file that will be deleted upon every run
JS_TEMP="$JS_DIR/_combined.js"
# The final output file
JS_COMBINED_FILE="$JS_DIR/combined.js"
# Get an array of all of the javascript files.
allFiles=(models/*.js)
# Create a new array of just the items that need to be moved to the front.
modelsToBeMovedForwards=(models/tab.js)
# Get the length of the allFiles array. There's a lot going on in this line.
# The $ indicates that we're 'getting' (rather than setting)
# {} indicates that this is an array
# The # says that we want the length
# [@] says we want all of the items in the array
length=${#allFiles[@]}
# Loop through the first array. Remove the items that need to be moved to the front.
for ((i=1; i<$length; i++))
do
# Call containsElement, declared above
containsElement "${allModels[$i]}" ${modelsToBeMovedForwards}
# If the results of the method, $?, is 1, remove this item from the array.
if [[ "$?" == "1" ]]; then
unset allModels[$i]
i=$i-1
fi
done
# Concatonate the arrays.
final=("${modelsToBeMovedForwards[@]}" "${allFiles[@]}")
# Loop through each item...
for F in ${final[@]}; do
CURR_FILE="$JS_DIR/$F"
# ... and shove it in our temp file using `cat`
cat $CURR_FILE >> $JS_TEMP
done
# Clear the old combined file
> $JS_COMBINED_FILE
# Compress the temp file into the real file using the YUI Compressor
java -jar yuicompressor-2.4.8.jar $JS_TEMP -o $JS_COMBINED_FILE
# Remove the temp files
rm $JS_TEMP
# Optional: Add the file to git.
# git add $JS_COMBINED_FILE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment