Reading a Standard Input Stream

Learn how to read a standard input stream using a while loop.

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 of the file with contacts. Let’s call it contacts.txt.

Alice=alice@gmail.com
Bob=(697) 955-5984
Eve=(245) 317-0117
Mallory=mallory@hotmail.com

Let’s write the script that reads this file. It is convenient to read the list of contacts directly into the associative array. This way, we will keep the searching mechanism over the list as effective as before.

When reading the file, we should handle its lines in the same manner. This means that we will repeat the same action several times. Therefore, we need a loop statement.

At the beginning of the loop, we don’t know the file size. Thus, we do not know the number of iterations to do. The while statement fits this case perfectly.

Why is the number of iterations unknown in advance?

This is because the script reads the file line by line. It cannot count the lines before it reads them all. There is an option to make two loops. Then, the first one counts the lines. The second loop processes them. However, this solution works slower and is less efficient.

We can call the built-in Bash command read for reading lines of the file. The command receives a string from the standard input stream. Then, it writes the string into the specified variable. We can pass the variable name as the parameter. Here is an example of calling read:

read var

Let’s run this command. Then, we type the string and press “Enter.” The read command writes our string into the var variable. We can call read without parameters. It writes the string into the reserved variable REPLY in this case.

Get hands-on with 1200+ tech skills courses.