Introduction to Shell programming
Unix/Linux command-line - One-liner "programs" at the command prompt (e.g. prog piped to prog).
Shell programming - Text file of multiple
(e.g. "if" condition then execute command, else other command).
The combination of one-liner command-line
a programmable User Interface, where you can quickly write
short programs to automate repetitive tasks.
= an interpreted program (i.e. not compiled).
Also known as a "Shell script" or "batch file" of UNIX commands.
Like .BAT files on Windows command line.
How to make a Shell program
- Put it in a directory that is in the PATH.
In this course we will put it in $HOME/bin
- It can have any extension (typically no extension).
- Put valid UNIX commands in it.
Make it executable:
$ chmod +x file
- Run it by typing its name:
$ file &
Alternative ways of working
- Pass program as arg to shell:
Advantage: Does not have to be executable. Does not have to be in PATH.
$ sh prog
Disadvantage: Have to type "sh" all the time.
Have to be in same directory (or else type more complicated path to program).
- Use file extension:
Advantage: Can easily see what the file is from a directory listing.
Disadvantage: Have to type the .sh
Could be used when no one ever types the name. (e.g. The script is only ever called by a program.)
I don't use either of these.
A Shell program is different to something typed on the command-line.
It can have arguments, and can exit at any point.
$1 1st command-line argument
$2 2nd command-line argument
$* all arguments
exit exit the Shell script
exit 0 exit with a return code that other progs can query
$? return code of last prog executed
# test if 1st argument = "0"
if test "$1" = "0"
echo "no - first argument is $1"