Premium lesson

Reading & Processing Input in Bash

Scripting·3 min read·Jan 1, 2025

In Bash, reading data from files or the standard input empowers scripts with data processing and user interactivity capabilities.

By reading from files, scripts can process data stored in various formats, such as configuration files, log files, or datasets, allowing for automated sorting, filtering, and analysis.

By reading from the standard input, scripts can adapt their behavior and logic according to the user's needs, enabling them to make choices during its execution, which ultimately improves its flexibility and configurability.

Reading from a file

To load the contents of a file at once and store it into a variable, you can combine the command substitution expansion $() with the cat command:

contents=$(cat filepath)

Where:

  • filepath is the filepath to the target file.

Example

Let's consider this file named lorem.txt located in the current directory:

Lorem ipsum dolor sit amet, consectetur adipiscing elit.Pellentesque non orci nisi.Curabitur vitae orci id mauris elementum rutrum.

Let's consider this script, that reads and outputs the contents of this file:

#!/bin/bash
icon light bulb key

Unlock the CLI & Scripting with Bash module

Learn how to gain advanced control over the OS and automate complex routine tasks prone to manual errors with the CLI and Bash scripting.

You get immediate access to:

  • 34 focused lessons across the CLI and Bash
  • 4 real-world projects with commented solutions
  • Ongoing updates to this bundle
  • Lifetime access to this bundle
Unlock this module