Search⌘ K
AI Features

Reading a Standard Input Stream

Understand how to read a standard input stream line by line in Bash scripts. Learn to use the read command with while loops to efficiently populate associative arrays from text files, manage delimiters, and separate data from code for better script maintenance.

We'll cover the following...

Contacts in an associative array

The while loop is well fit for handling an input stream. Here is an example of such a task. Let’s suppose that we need a script that reads a text file. It should make an associative array from the file content.

Let’s consider the contacts.sh script for managing the list of contacts:

#!/bin/bash

declare -A contacts=(
["Alice"]="alice@gmail.com"
["Bob"]="(697) 955-5984"
["Eve"]="(245) 317-0117"
["Mallory"]="mallory@hotmail.com")

echo "${contacts["$1"]}"

The script stores contacts in the format of the Bash array declaration. This makes adding a new person to the list inconvenient. The user must know the Bash syntax. Otherwise, they can make a mistake when initializing an array element, which will break the script.

There is a solution to the problem of editing the contacts list. We can move the list into a separate text file. Then, the script would read it at startup. This way, we separate the data and code, which is widely considered a best practice in software development.

The following listing shows a possible format ...