Dr. Mark Humphrys

School of Computing. Dublin City University.

Home      Blog      Teaching      Research      Contact

Search:

CA249      CA318      CA425      CA651

w2mind.computing.dcu.ie      w2mind.org


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
then
 rm f1
else
 rm f2
fi
Make it executable:
$ chmod +x file
Make sure it is in the PATH and just run it:
$ file
$ file &



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.
$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


Flow of control, test



# test if 1st argument = "0"

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




Feeds      HumphrysFamilyTree.com

Bookmark and Share           On Internet since 1987.