read - macOS


Overview

read reads a line from the standard input and stores it in a shell variable. It is typically used to capture user input or the output of other commands.

Syntax

read [flags]... [variable]

Options/Flags

  • -d, –delimiter=: Specifies the delimiter to separate input fields. Default: space
  • -e, –editor=: Launches the specified editor to edit the input.
  • -n, –number=: Reads only the specified number of characters.
  • -p, –prompt=: Displays the provided prompt before reading input.
  • -r, –raw=: Disables character interpretation (e.g., backslash escapes).
  • -s, –silent=: Suppresses input echoing.
  • -t, –timeout=: Sets a read timeout in seconds.

Examples

Basic usage:

read name
echo "Hello $name"

Using a delimiter:

read -d ":" name age
echo "Name: $name, Age: $age"

Using a prompt:

read -p "Enter your name: " name

Using a timeout:

read -t 5 name
echo "You took too long!"

Common Issues

  • Blank input: Using -t without -n can result in blank input if the user presses Enter without typing.

  • Oversized input: If the input length exceeds the specified -n value, it may be truncated or cause errors.

Integration

  • With other commands: read can be used to capture the output of other commands, such as find or grep.
  • In scripts: read is often used in scripts to read input parameters or control flow based on user responses.
  • echo: Prints output to the console.
  • printf: Formats and prints output.
  • tr: Translates, squeezes, or deletes characters.