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