DistributedNetworks DistributedNetworks

Shell Programming  «Prev  Next»
Lesson 8

Defining Shell Programming - Conclusion

This module introduced you to the UNIX shell as a programming environment and compared it to other programming environments that are available. You learned about different shells that UNIX supports and what features distinguish them. You also explored a sample script in UNIX and saw how shell scripts are useful in many circumstances. The difference between interpreted languages like shell scripts and compiled languages like C was discussed. Based on the information about different programming tools, you learned why different tools are chosen to complete different tasks.

Loops and Branches

Operations on code blocks are the key to structured and organized shell scripts. Looping and branching constructs provide the tools for accomplishing this.
A loop is a block of code that iterates a list of commands as long as the loop control condition is true.
for loops
for arg in [list]
This is the basic looping construct. It differs significantly from its C counterpart.
for arg in [list]

During each pass through the loop, arg takes on the value of each successive variable in the list.
for arg in "$var1" "$var2" "$var3" ... "$varN"
# In pass 1 of the loop, arg = $var1
# In pass 2 of the loop, arg = $var2
# In pass 3 of the loop, arg = $var3
# ...
# In pass N of the loop, arg = $varN
# Arguments in [list] quoted to prevent possible word splitting.

The argument list may contain wild cards. If do is on same line as for, there needs to be a semicolon after list.
for arg in [list] ; do

Example 2-8 Simple for loops

# Listing the planets.
for planet in Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune Pluto
echo $planet # Each planet on a separate line.

In addition, this module discussed how the shell is a command programming language that provides an interface to the UNIX operating system. Its features include
  1. control-flow primitives,
  2. parameter passing,
  3. variables and string substitution.
Constructs such as while, if then else, case and for are available. Two-way communication is possible between the shell and commands.
String-valued parameters, typically file names or flags, may be passed to a command. A return code is set by commands that may be used to determine control-flow, and the standard output from a command may be used as shell input.
The shell can modify the environment in which commands run. Input and output can be redirected to files, and processes that communicate through pipes can be invoked. Commands are found by searching directories in the file system in a sequence that can be defined by the user. Commands can be read either from the terminal or from a file, which allows command procedures to be stored for later use.