Chris Lamb

Scrap your boilerplate; POSIX shell edition

I don't remember where I saw this first - probably in the Debian Installer code. Anyway, given an n-tuple it can be somewhat unwieldy to unpack it:

VAR="Aho Sethi Ullman"
ONE="$(echo ${VAR} | cut -d' ' -f1)"
TWO="$(echo ${VAR} | cut -d' ' -f2)"
THREE="$(echo ${VAR} | cut -d' ' -f3)"

The trick being presented is to generate the boilerplate code and then eval it:

VAR="Aho Sethi Ullman"
eval $(echo ${VAR} | awk '{ print "ONE=" $1 " TWO=" $2 " THREE=" $3 }')

Here's a more concrete example, with apologies to Python:

for PAIR in \
           "one    Aho" \
           "two    Sethi" \
           "three  Ullman"
    eval $(echo ${PAIR} | awk '{ print "k=" $1 " v=" $2 }')

    # .. do something with $k and $v

Chris Lamb is a freelance software developer and the current Debian Project Leader. You can read other posts by me, see software I have written or read more about me. You can also follow me @lolamby.

Tags: Hacks

Planets: ALUG UWCS Debian WUGLUG

Thursday 5th February 2009

Five comments