Script for Managing the Contacts

Learn how the read command can process files.

We'll cover the following

Using read

Let’s consider that contacts.txt contains the following content.

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

Here is an example to read the first line of the contacts.txt file. The following command does it:

read -r contact < contacts.txt

This command writes the Alice=alice@gmail.com string to the contact variable.

We can write the name and contact information to two different variables. We need to define the equal sign as a delimiter to do that. Then, we will get the following read call:

IFS=$'=' read -r name contact < contacts.txt

Now, the name variable gets the “Alice” name. The e-mail address comes to the contact variable.

Let’s try the following while loop for reading the entire contacts.txt file:

while IFS=$'=' read -r name contact < "contacts.txt"
do
  echo "$name = $contact"
done

Unfortunately, this approach does not work because it’ll accidentally create an infinite loop. This happens because the read command always reads only the first line of the file. Then, it returns the zero exit status. The zero status leads to another execution of the loop body, which then leads to another zero status, and so on in a continuing cycle.

We should force the while loop to pass through all lines of the file. The following form of the loop does it:

while CONDITION
do
  ACTION
done < FILE

This form of the loop can handle keyboard input too. We need to specify the /dev/tty input file for doing that. Then, the loop will read keystrokes until we press Ctrl+D.

Here is the corrected while loop that reads the entire contacts.txt file:

while IFS=$'=' read -r name contact
do
  echo "$name = $contact"
done < "contacts.txt"

This loop prints all lines of the contacts file.

There is the last step left to finish our script. We should write the name and contact variables to the associative array on each iteration. The name variable is the key and contact is the value.

The file while-contacts.sh shows the final version of the script for reading the contacts from the file. We can execute the file on following commands:

./while-contacts.sh "Alice"
./while-contacts.sh "Bob"

Get hands-on with 1200+ tech skills courses.