In EBCDIC we trust.

November 20, 2012

shell templates

Via Shocco, a neat little technique for templating in shell. The idea is to encapsulate a here document in a function, and use the function arguments ($1 $2 ...) as the template variables. The cool part is the use of $(cat) in the template body, allowing you to pipe in data to the function and have it wrapped in the output. This is extremely useful in the middle of a pipeline; much of shocco is, in fact, a gigantic pipeline.

Here's a simple example. We assume the input is already properly escaped for HTML.

layout() {
  cat <<HTML

echo 'My body is ready' | layout 'Status'


<body><p>My body is ready</p></body>

Shocco is shoc-full (sorry) of interesting shell techniques and I'd recommend checking it out if you're at all into shell programming.