Dr. Mark Humphrys

School of Computing. Dublin City University.

Home      Blog      Teaching      Research      Contact


CA216      CA249      CA318

CA400      CA651      CA668

Introduction to Shell

Shell gives you a quick and powerful way of having a programmable User Interface, where you can quickly write short programs to automate repetitive tasks.

I have had a changing collection of my own personal shell scripts moving with me from place to place and machine to machine since the 1980s. It is I think the only technology that I have found useful for that entire period.

Shell program = 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.

Shell program can have any extension (typically no extension). Edit a file, put some UNIX commands in it, perhaps strung together with some logic:

if condition
 rm f1
 rm f2
Make it executable:
$ chmod +x file
Make sure it is in the PATH and just run it:
$ file
$ file &

Alternative ways of working

If script is not executable you can run it this way:
$ sh prog
Advantage: Don't have to worry about chmod or PATH.
Disadvantage: Have to type "sh" all the time. Have to be in same directory (or else type path).

Some people like to end scripts with an extension:
$ prog.sh
$ sh prog.sh
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. I make scripts executable, put them in PATH, and use no extensions. Then I just type:
$ prog

Pipes and redirection in scripts

Remember pipes and redirection on command line.

Arguments and returns

$*           all arguments to the Shell program
$1           1st argument, etc.
$@           like $* except deals differently with arguments with spaces and wildcards

$0		name of prog
$#		no. of args

#                       comment

shift		shift args leftwards 
		this is useful if you want to remove some of the first args, then "shift" a couple of times,
		and then do "for i in $*" with the remaining args
		e.g. grep (switches) (string) file1 ... filen

exit		exit the Shell script
exit 0		exit with a return code that other progs can query

$?		return code of last prog executed
		e.g. quiet grep: 
		 grep > /dev/null 
		and then check $?
		though grep may have -q (quiet) option anyway

if, test and flow of control

# test if 1st argument = "0"

if test "$1" = "0"
 echo "yes"
 echo "no - first argument is $1"

Feeds      w2mind.org

On Internet since 1987.