AI Features

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 ...