Chapter 6. So, you want an Argument?

Table of Contents

Introduction
Positional Parameters 0 and 1 through 9
Exercises:
Challenge sequence:
Other arguments used with positional parameters
$# How many positional arguments have we got ?
$* - display all positional parameters
Using the "shift" command - for more than 9 positional parameters
Exit status of the previous command

Introduction

It may be necessary, or even more efficient, to be able to specify arguments when executing a shell script from the command line.

For example, if you run the sort command you could send it some arguments:

sort +o -r -n
            

It would be nice to be able to send scripts arguments in a similar fashion.

Example:

If we had a program to look up your favourite restaurants, we might have a big file of restaurant names and telephone numbers. Let's say that we wanted to just extract the one telephone number for a certain restaurant.

Or we might want to also classify the types of restaurants with keywords according to what they are. So lets say our restaurants.txt file contained rows of the following format:

<Type>,<Restaurant>,<Name>,<Tel Number>,<rating>	
            

So enter the following data into a file called restaurants.txt:

smart,Parks,6834948,9
italian,Bardellis,6973434,5
steakhouse,Nelsons Eye,6361017,8 
steakhouse,Butchers,Grill,6741326,7
smart,Joes,6781234,5
            
[Note] Note

For the purposes of these exercises, and to make things a little easier for you, the reader, the top restaurant can only have a rating of 9. The worst will have a rating of 0.

So, we've got a file that represents our favourite restaurants. It would be nice to have a script to say:

./eatout.sh italian 
            

or

./eatout.sh steakhouse 
            

This would then take the type of food we want to eat, and it would show us the details for the restaurant(s) that would fit our required description.

What I'm heading towards is writing a script that will take a argument and show us only those restaurants that we're interested in eating at.