units - Linux


Overview

The units command in Linux is a utility for converting between different units of measurement. Primarily used for conversion of quantities from one unit of measure to another, it facilitates tasks involving numerical computations with different measurement units, making it especially useful in fields such as engineering, physics, and everyday problem solving where precision is crucial.

Syntax

The basic syntax of the units command is as follows:

units [options] [from-unit to-unit]
  • from-unit: The unit you are converting from.
  • to-unit: The unit you are converting to.

To use units interactively, just type units and hit enter. You will be prompted to enter the units you wish to convert.

Options/Flags

  • -h, --help: Display help content and exit.
  • -l, --list: List all known units and prefixes.
  • -q, --quiet: Suppresses prompting and other non-essential output, useful for scripting.
  • -v, --version: Display version information and exit.
  • -c, --check: Check the units database for consistency.
  • -f FILE, --file=FILE: Specify a file of unit definitions to supplement or replace the default unit definitions.

Examples

  1. Basic Conversion: Converting 100 feet to meters.

    units '100 feet' 'meters'
    

    Output might be 30.48 meters.

  2. Complex Conversion: Converting 10 gallons per minute to liters per second.

    units '10 gallons/minute' 'liters/second'
    

    Output could be approximately 0.631 liters/second.

  3. Using Custom Units File: Define custom units and perform conversion using them.

    units -f custom_units.txt '1 marathon' 'kilometers'
    

Common Issues

  • Unknown Units Error: This happens when units does not recognize one of the units specified. Ensure spelling is correct, the unit exists, or you may need to define it in a custom units file.
  • Non-compatible Units: Trying to convert between incompatible units (like meters to seconds) will result in an error. Check that the units are compatible.

Integration

units can be integrated with shell scripts for automated calculations. For example, you can process a file of conversions:

while read line; do
    units "$line"
done < conversions.txt

This script reads lines from conversions.txt, each containing a conversion command, and executes them.

  • awk: Useful for processing numeric output in scripts.
  • bc: For performing precise arithmetic in scripts.

Refer to the official GNU units documentation here for more comprehensive details and a complete list of units and prefixes.