February 5th 2009

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"
do
    eval $(echo ${PAIR} | awk '{ print "k=" $1 " v=" $2 }')

    # .. do something with $k and $v
done



You can subscribe to new posts via email or RSS.