Anatomy of a shell script


A typical Bourne shell script starts with the line #!/bin/sh. This is an instance of a general UNIX mechanism that allows arbitrary script interpreters to be invoked with #!/path/to/interpreter, and is not strictly necessary for Bourne shells scripts since usually unrecognized executables are fed to /bin/sh by default, but it's not a bad idea to be explicit.

A script consists of these basic constructs:

UNIX commands, usually much as you would type them
grep foo file | sort
Syntax for selection and looping
for name in *; do if [ -d $name ]; then echo $name; fi; done
Syntax for setting and referring to variables and shell options
PATH=/usr/local/bin:/usr/bin/:bin; export PATH; echo $PATH
Comments (start with # through end of line)
echo $PATH # display PATH on terminal

For the complete lowdown on shell syntax, look through man sh, but I'll go on to describe some of the common features.

Next ->


Steve VanDevender
Last modified: Tue Jul 8 10:15:49 PDT 2003