Making decisions
Consider the following problem: 'If file A is
smaller than 100 lines then display it on the terminal, otherwise
tell me that it's bigger than 100 lines.' How would you set about
programming that using the shell? We can find out how many lines
are in A using wc , we can print a file,
and we can display a message. However the only method we have so
far met for deciding to execute commands conditionally is to use
|| or && and the exit status of a
command. We would ideally like a command A_is_small
which succeeds (exit status 0) if A is smaller than
100 lines. Our script might then look like:
(A_is_small && more A) || echo A is too
big
The fundamental method by which the shell allows you to make
choices as to what to do next in a script is by use of the exit
status of a command. We can't in general expect commands such as
A_is_small to exist already - there must be a more
general method of translating such statements into things the shell
can understand, which will return an appropriate exit status. We
need to be able to compare numbers (such as file sizes) and strings
(values of environment variables), and to interrogate easily the
existence and access permissions of files.
|