Script Your Build

If you do any sort of modern web development, chances are you use a preprocessor like SASS or Coffeescript. You might also use a build tool like gulp, grunt, or broccoli to do live re-compilation of all your assets.

However, these build tools can be complicated to set up. Most preprocessors come with built-in file watching, such as sass --watch, and with a simple bash script, you can put together a poor man's build tool that will start and stop the preprocessors simultaneously.

The hitch is that running a preprocessor in watch mode typically runs the process in the foreground, which prevents us from running more than one at once. Therefore, we want to run them in parallel in the background, using the ampersand operator &.

This however presents us with another problem: your script will not kill background processes automatically when it exits. The final piece we need is to add a call to trap, to ensure we also send a kill signal to these background processes when our script is killed.

Putting everything together:


# send kill to all subprocesses if parent script receives
# SIGNIT/SIGTERM/EXIT. -$$ is the group of this process
# and all child processes
trap "kill -- -$$" SIGINT SIGTERM EXIT

# run sass compilation in a background shell
( cd stylesheets && sass --watch app.sass ) &

# run coffescript compilation in a background shell
( cd javascripts && coffee --compile --watch ) &

# wait for kill signal