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