expr - Linux


Overview

The expr command in Linux is used for expression evaluation. It primarily handles arithmetic, logical, and string operations from the command line or in shell scripts. expr can be very effective in scenarios where simple calculations, comparisons, or string manipulations are required without launching a full scripting environment.

Syntax

The basic syntax of the expr command is as follows:

expr EXPRESSION

Where EXPRESSION can be an arithmetic operation, a comparison, or a string operation. It is important to note that expressions involving operators should have spaces around them to avoid being interpreted as a single string.

Options/Flags

expr does not have many options, but understanding its basic usage is crucial:

  • --help: Display a help message and exit.
  • --version: Output version information and exit.

Most of the functionality comes from the types of expressions you can evaluate:

Examples

  1. Arithmetic Operation:
    Calculate the sum of two numbers:

    expr 5 + 3
    

    Outputs: 8

  2. Logical Operations:
    Evaluate if one number is greater than another:

    expr 10 \> 5
    

    Outputs: 1 (true), returns 0 if false.

  3. String Length:
    Get the length of a string:

    expr length "Hello World"
    

    Outputs: 11

  4. Substring Extraction:
    Extract substring starting at position 2 of length 5:

    expr substr "Hello World" 2 5
    

    Outputs: ello

  5. Using expr in Shell Scripts:
    Use expr in a bash script to calculate values dynamically:

    #!/bin/bash
    a=10
    b=20
    result=$(expr $a + $b)
    echo $result
    

    This script calculates the sum of a and b and prints 30.

Common Issues

  • Syntax Errors: The most common issue is related to not using spaces around operators. Ensure each part of the expression is separated by spaces.
  • Handling Non-numeric Strings: Trying to perform arithmetic on non-numeric strings returns an error. Make sure all operands are numeric or use string operations.

Integration

expr is commonly used within shell scripts or in combination with other Unix commands in pipelines. For example, you can use expr to calculate loop boundaries or to process numeric command-line arguments.

Example:

#!/bin/bash
for i in $(seq 1 $(expr $1 - 1))
do
   echo "Count: $i"
done

This script prints numbers from 1 to one less than the number passed as a command-line argument.

  • awk: A powerful text processing tool that can also handle expressions.
  • sed: Stream editor for filtering and transforming text, which also supports basic math in some implementations.
  • let: Another shell built-in for arithmetic operations, more straightforward for pure arithmetic compared to expr.

For further reading, the official GNU documentation for coreutils which includes expr can be found here.