Shell Functions
As programs get longer and more complex, they
become more difficult to design, code, and
maintain. As with any large endeavor, it is often
useful to break a single, large task into a number
of smaller tasks.
In this lesson, we will begin to break our
single monolithic script into a number of separate
functions.
To get familiar with this idea, let's consider
the description of an everyday task -- going to the
market to buy food. Imagine that we were going to
describe the task to a man from Mars.
Our first top-level description might look like
this:
- Leave house
- Drive to market
- Park car
- Enter market
- Purchase food
- Drive home
- Park car
- Enter house
This description covers the overall process of
going to the market, however a man from Mars will
probably require additional detail. For example,
the "Park car" sub task could be described as
follows:
- Find parking space
- Drive car into space
- Turn off motor
- Set parking brake
- Exit car
- Lock car
Of course the task "Turn off motor" has a number
of steps such as "turn off ignition" and "remove
key from ignition switch" and so on.
This process of identifying the top-level steps
and developing increasingly detailed views of those
steps is called top-down design. This
technique allows you to break large complex tasks
into many small, simple tasks.
As our script continues to grow, we will use top
down design to help us plan and code our
script.
If we look at our script's top level tasks, we
find the following list:
- Open page
- Open head section
- Write title
- Close head section
- Open body section
- Write title
- Write time stamp
- Close body section
- Close page
All of these tasks are implemented but we want
to add more. Let's insert some additional tasks
after task 7:
- Write time stamp
- Write system release info
- Write up-time
- Write drive space
- Write home space
- Close body section
- Close page
It would be great if there were commands that
did these additional tasks. If there were, we could
use command substitution to place them in our
script like so:
|