Here's a roughly modified version of your script:
$ more cmd.bash
#!/bin/bash
echo "Whose phone number do you want to know?"
read name
number=$(grep "$name" telephone | cut -d';' -f2)
echo ''
echo "The phone number of $name is $number."
It works as follows:
$ ./cmd.bash
Whose phone number do you want to know?
Hans
The phone number of Hans is 015253694.
How it works
It simply takes in the name via the read name
command and stores what was typed in the variable, $name
. We then grep through the file telephone
and then use cut
to split the resulting line from the file telephone
into 2 fields, using the semicolon as the separation character. The phone number, filed 2, is stored in the variable $number
.
Testing
You can use the following script to test that your script works, using the data from the file telephone
.
$ while read -r i ;do
echo "-----"
echo "Test \"$i\""
./cmd.bash <<<$i
echo "-----"
done < <(cut -d';' -f1 telephone)
The above commands read in the contents of the file telephone
, split it on the semicolon, ;
, and then takes each value from field 1 (then names) and loops through them 1 at a time. Each name is then passed to your script, cmd.bash
, via STDIN, aka. <<<$i
. This simulates a user typing in each of the names.
$ while read -r i ;do echo "-----"; echo "Test \"$i\""; \
./cmd.bash <<<$i; echo "-----"; done < <(cut -d';' -f1 telephone)
-----
Test "Jan"
Whose phone number do you want to know?
The phone number of Jan is 032569874.
-----
-----
Test "Annemie"
Whose phone number do you want to know?
The phone number of Annemie is 014588529.
-----
-----
Test "Hans"
Whose phone number do you want to know?
The phone number of Hans is 015253694.
-----
-----
Test "Stefaan"
Whose phone number do you want to know?
The phone number of Stefaan is 011802367.
-----
awk
does pattern matching, so thegrep
is redundant (and the pipe an overhead)... – jasonwryan Nov 22 '14 at 19:00