Shell Programming

In Section 4.5 in Chapter 4, we discussed the various shells available for Linux, but something should be said about them in terms of programming. The differences come through most clearly when it comes to writing shell scripts. The Bourne shell and C shell command languages are slightly different, but the distinction is not obvious with most normal interactive use. In fact, many of the distinctions arise only when you attempt to use bizarre, little-known features of either shell, such as word substitution or some of the more oblique parameter expansion functions.

The most notable difference between Bourne and C shells is the form of the various flow-control structures, including if ...then and while loops. In the Bourne shell, an if ...then takes the form:

if list 
then 
  commands 
elif list 
then 
  commands 
else 
  commands 
fi

where list is just a sequence of commands (more generally called “pipelines”) to be used as the conditional expression for the if and elif (short for “else if”) commands. The conditional is considered to be true if the exit status of the list is zero (unlike Boolean expressions in C, in shell terminology an exit status of zero indicates successful completion). The commands enclosed in the conditionals are simply commands to execute if the appropriate list is true. The then after each list must be on a new line to distinguish it from the list itself; alternately, you can terminate the list with a ;. The same holds true for the commands.

An example ...

Get Running Linux, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.