expr - macOS


Overview

The expr command in macOS is a utility for evaluating expressions. This command processes a given expression and displays its result. It supports operations like arithmetic, comparison, and string manipulation among others. Common use cases include performing basic arithmetic, extracting substrings, and manipulating strings directly within shell scripts or command line.

Syntax

The basic syntax of the expr command is as follows:

expr expression

Here, expression can be a combination of items like numbers, strings, or operators. Expressions are written as arguments separated by spaces, and careful use of quoting is necessary to avoid shell interpretation.

Options/Flags

expr does not have many options or flags but instead focuses on the expressions it evaluates:

  • --: Indicates the end of options. Everything following -- is treated as operands, even if they begin with a ‘-‘.

Expressions within expr support various operators, grouped by the order of their precedence:

  1. | : Returns the first operand if it is neither null nor zero; otherwise, returns the second operand.
  2. & : Returns the first operand if neither operand is null or zero; otherwise, returns zero.
  3. = , > , >= , < , <= , != : Comparison operators return 1 if true, and 0 if false.
  4. +, - : Addition and subtraction.
  5. *, /, % : Multiplication, division, and modulus.

Examples

Here are some examples of how to use expr:

  1. Arithmetic Calculation:

    expr 10 + 20
    

    Output: 30

  2. Comparison:

    expr 10 \> 5
    

    Output: 1 (true)

  3. Substring Extraction:

    expr substr "Hello World" 4 5
    

    Output: lo Wo

  4. String Length:

    expr length "Hello"
    

    Output: 5

  5. Regular Expression Matching:

    expr "Hello World" : 'Hello \(.*\)'
    

    Output: World

Common Issues

  • Quoting and Escaping Characters: The most common issue is not properly quoting expressions, leading to unexpected results or syntax errors.
  • Division by Zero: This will throw an error. Always check for a zero divisor in scripts.
  • Misuse of Operators: Ensure the correct operator precedence and format; use spaces between operators and operands.

Integration

expr can be integrated with other shell commands for more complex scripts. For example, using expr to process file size information:

size=$(ls -l myFile.txt | awk '{ print $5 }')
count=$(expr $size / 1024)
echo "Size in KB: $count"

This script extracts the size of myFile.txt and converts it to KB.

  • awk: Useful for pattern scanning and processing.
  • sed: Stream editor for filtering and transforming text.
  • test or [ ]: Evaluate expressions within shell scripts.

For further reading, official documentation can be consulted via the man expr command in your terminal, providing more detailed information about expression handling and options.