CSC128 : Introduction to UNIX

Basic Shell Programming


Simple Shell Scripts

The simplest form of a shell script is just a text file containing UNIX commands, one per line.  The commands will be executed, in order, the same as if they had been typed in by hand.  

To make a text file executable, give it executable permissions with
chmod.

Comments

Lines that start with a hash mark (#, pound sign) are ignored by the shell.  You can add comments to long shell scripts by starting lines with #'s, and including whatever comment text you would like on the rest of the line.  Note that only lines starting with # are ignored.


Specifying the Shell to Use

Different shells behave differently.  To force your script to use a specific shell, the first character of the file must be a hash mark (#), an exclamation mark (!), and the absolute path to the shell you wish to use.  Shells that we will use in this class include:

#!/bin/sh
#!/usr/bin/bash
#!/bin/bash

It is good practice to always begin your shell script with a shell specification.  If it isn't there, it will run on whatever shell the user is using, and as we will see later, many commands are very different on different shells;  any non-trivial script is unlikely to run correctly on more than one shell.


Toolbox

Filename Substitution
You can use special characters in filenames to indicate mulitiple files.  The shell interprets these characters as "wildcards" and expands them to every file that fits the "wildcard".

?
The question mark will match any single character.  For example:
$ ls
lab1.txt lab2.txt proj1.txt proj2.txt proj3.txt
quiz1.txt quiz2.txt

$ ls proj?.txt
proj1.txt proj2.txt proj3.txt

*
The asterisk (or star) will match any contiguous group of characters. For example:
$ ls
lab1.txt lab2.txt proj1.txt proj2.txt proj3.txt
quiz1.txt quiz2.txt

$ ls *1.txt
lab1.txt proj1.txt quiz1.txt


[]
The brackets are similar to the question mark, except that you can specify a list of possible matching characters.  For example:
$ ls
lab1.txt lab2.txt proj1.txt proj2.txt proj3.txt
quiz1.txt quiz2.txt

$ ls proj[12].txt
proj1.txt proj2.txt

echo
echos its arguments to stdout.  This is useful to display information to the user, or to pipe a string to another program. For example:
$ echo My dog has fleas.
My dog has fleas.

$ echo My dog has fleas. > test
$ more test
My dog has fleas.

date
displays on stdout what date and time UNIX thinks it is.

whoami
displays on stdout the name of the current user.

lpr
lpr [filename]
sends the file named [filename] to the default printer.  If no file is specified, then it sends stdin to the printer.  For example, ls -l | lpr  will send a long listing to the default printer.