Next: , Previous: , Up: Units Conversion   [Contents][Index]


11 Scripting with units

Despite its numerous options, units cannot cover every conceivable unit-conversion task. For example, suppose we have found some mysterious scale, but cannot figure out the units in which it is reporting. We reach into our pocket, place a 3.75-gram coin on the scale, and observe the scale reading ‘0.120’. How do we quickly determine the units? Or we might wonder if a unit has any “synonyms,” i.e., other units with the same value.

The capabilities of units are easily extended with simple scripting. Both questions above involve conformable units; on a system with Unix-like utilities, conversions to conformable units could be shown accomplished with the following script:

#!/bin/sh

progname=`basename $0 .sh`
umsg="Usage: $progname [<number>] unit"

if [ $# -lt 1 ]
then
    echo "$progname: missing quantity to convert"
    echo "$umsg"
    exit 1
fi

for unit in `units --conformable "$*" | cut -f 1 -d ' '`
do
    echo "$*"   # have -- quantity to convert
    echo $unit  # want -- conformable unit
done | units --terse --verbose

When units is invoked with no non-option arguments, it reads have/want pairs, on alternating lines, from its standard input, so the task can be accomplished with only two invocations of units. This avoids the computational overhead of needlessly reprocessing the units database for each conformable unit, as well as the inherent system overhead of process invocation.

By itself, the script is not very useful. But it could be used in combination with other commands to address specific tasks. For example, running the script through a simple output filter could help solve the scale problem above. If the script is named conformable, running

$ conformable 3.75g | grep 0.120

gives

        3.75g = 0.1205653 apounce
        3.75g = 0.1205653 fineounce
        3.75g = 0.1205653 ozt
        3.75g = 0.1205653 tradewukiyeh
        3.75g = 0.1205653 troyounce

So we might conclude that the scale is calibrated in troy ounces.

We might run

$ units --verbose are
        Definition: 100 m^2 = 100 m^2

and wonder if ‘are’ has any synonyms, value. To find out, we could run

$ conformable are | grep "= 1 "
        are = 1 a
        are = 1 are

Next: Output Styles, Previous: Invoking units, Up: Units Conversion   [Contents][Index]