Vous êtes sur la page 1sur 15

1. Log on a Linux machine or connect to one from a Windows machine (e.g.

on the Exceed icon and then use putty to connect to the server kiwi. Enter your
login (user name) and password at relevant prompts.
2. Enter these commands at the U!" prompt# and try to interpret the output. $sk
%uestions and don&t 'e afraid to experiment (as a normal user you cannot do much
o echo hello world
o passwd
o date
o hostname
o arch
o uname -a
o dmesg | more (you may need to press q to %uit)
o uptime
o who am i
o who
o id
o last
o finger
o w
o top (you may need to press q to %uit)
o echo $SHELL
o echo {con,pre}{sent,fer}{s,ed}
o man automatic door
o man ls (you may need to press q to %uit)
o man who (you may need to press q to %uit)
o who can tell me wh! i got di"orced
o lost
o clear
o cal #$$$
o cal % &'(# (do you notice anything unusual))
o )c -l (type quit or press *trl+d to %uit)
o echo (*+ | )c -l
o !es please (you may need to press *trl+c to %uit)
o time sleep (
o histor!
,. -ry the following command se%uence(
o cd
o pwd
o ls -al
o cd ,
o pwd (where did that get you))
o cd ,,
o pwd
o ls -al
o cd ,,
o pwd
o ls -al
o cd ,,
o pwd (what happens now)
o cd -etc
o ls -al | more
o cat passwd
o cd -
o pwd
4. *ontinue to explore the filesystem tree using cd# ls# pwd and cat. Look in -)in# -usr-)in#
-s)in# -tmp and -)oot. What do you see)
5. Explore -de". *an you identify what devices are availa'le) Which are character+oriented
and which are 'lock+oriented) *an you identify your tty (terminal) device (typing who am
i might help). who is the owner of your tty (use ls -l))
6. Explore -proc. /isplay the contents of the files interrupts# de"ices# cpuinfo# meminfo
and uptime using cat. *an you see why we say -proc is a pseudo+filesystem which
allows access to kernel data structures)
7. *hange to the home directory of another user directly# using cd .username.
0. *hange 'ack into your home directory.
9. 1ake su'directories called work and pla!.
10. /elete the su'directory called work.
11. *opy the file -etc-passwd into your home directory.
12. 1ove it into the su'directory pla!.
13. *hange into su'directory pla! and create a sym'olic link called terminal that points to
your tty device. What happens if you try to make a hard link to the tty device)
14. What is the difference 'etween listing the contents of directory play with ls -l and ls
15. *reate a file called hello,t/t that contains the words 2hello world2. *an you use 2cp2
using 2terminal2 as the source file to achieve the same effect)
16. *opy hello,t/t to terminal. What happens)
17. !magine you were working on a system and someone accidentally deleted the ls
command (-)in-ls). 3ow could you get a list of the files in the current directory) -ry it.
18. 3ow would you create and then delete a file called 2$SHELL2) -ry it.
19. 3ow would you create and then delete a file that 'egins with the sym'ol 0) -ry it.
20. 3ow would you create and then delete a file that 'egins with the sym'ol -) -ry it.
21. What is the output of the command( echo {con,pre}{sent,fer}{s,ed}) ow# from your
home directory# copy -etc-passwd and -etc-group into your home directory in one
command given that you can only type -etc once.
22. 4till in your home directory# copy the entire directory pla! to a directory called work#
preserving the sym'olic link.
23. /elete the work directory and its contents with one command. $ccept no complaints or
24. *hange into a directory that does not 'elong to you and try to delete all the files (avoid
-proc or -de"# 5ust in case6)
25. Experiment with the options on the ls command. What do the d# i# 1 and 2 options do)
1. /escri'e three different ways of setting the permissions on a file or directory to
r--r--r--. *reate a file and see if this works.
2. -eam up with a partner. *opy -)in-sh to your home directory. -ype 2chmod *s
sh2. *heck the permissions on sh in the directory listing. ow ask your partner to
change into your home directory and run the program ,-sh. $sk them to run the
id command. What&s happened) 7our partner can type e/it to return to their
3. What would happen if the system administrator created a sh file in this way) Why
is it sometimes necessary for a system administrator to use this feature using
programs other than sh)
4. /elete sh from your home directory (or at least to do a chmod -s sh).
8. 1odify the permissions on your home directory to make it completely private.
*heck that your partner can&t access your directory. ow put the permissions 'ack
to how they were.
6. -ype umask $$$ and then create a file called world,t/t containing the words
2hello world2. Look at the permissions on the file. What&s happened) ow type
umask $## and create a file called world#,t/t. When might this feature 'e useful)
7. *reate a file called 2hello,t/t2 in your home directory using the command cat
-u 3 hello,t/t. $sk your partner to change into your home directory and run
tail -f hello,t/t. ow type several lines into hello,t/t. What appears on your
partner&s screen)
8. Use find to display the names of all files in the -home su'directory tree. *an you
do this without displaying errors for files you can&t read)
9. Use find to display the names of all files in the system that are 'igger than 91:.
10. Use find and file to display all files in the -home su'directory tree# as well as a
guess at what sort of a file they are. /o this in two different ways.
11. Use grep to isolate the line in -etc-passwd that contains your login details.
12. Use find and grep and sort to display a sorted list of all files in the -home
su'directory tree that contain the word hello somewhere inside them.
13. Use locate to find all filenames that contain the word emacs. *an you com'ine
this with grep to avoid displaying all filenames containing the word li))
14. *reate a file containing some lines that you think would match the regular
expression( 456$-%7{&,(}6a-89-8 7*$:|none and some lines that you think would
not match. Use egrep to see if your intuition is correct.
15. $rchive the contents of your home directory (including any su'directories) using
tar and cpio. *ompress the tar archive with compress# and the cpio archive with
g8ip. ow extract their contents.
16. ;n Linux systems# the file -de"-urandom is a constantly generated random stream
of characters. *an you use this file with od to printout a random decimal num'er)
17. -ype mount (with no parameters) and try to interpret the output.
1. $rchive the contents of your home directory using tar. *ompress the tar file with
g8ip. ow uncompress and unarchive the ,tar,g8 file using cat# tar and g8ip on
one command line.
2. Use find to compile a list of all directories in the system# redirecting the output so
that the list of directories ends up in a file called directories,t/t and the list of
error messages ends up in a file called errors,t/t.
3. -ry the command sleep (. What does this command do)
4. <un the command in the 'ackground using ;.
5. <un sleep &( in the foreground# suspend it with *trl+= and then put it into the
'ackground with )g. -ype <o)s. -ype ps. :ring the 5o' 'ack into the foreground
with fg.
6. <un sleep &( in the 'ackground using ;# and then use kill to terminate the
process 'y its 5o' num'er. <epeat# except this time kill the process 'y specifying
its >!/.
7. <un sleep &( in the 'ackground using ;# and then use kill to suspend the
process. Use )g to continue running the process.
8. 4tartup a num'er of sleep =$ processes in the 'ackground# and terminate them all
at the same time using the pkill command.
9. Use ps# w and top to show all processes that are executing.
10. Use ps -aeH to display the process hierarchy. Look for the init process. 4ee if
you can identify important system daemons. *an you also identify your shell and
its su'processes)
11. *om'ine ps -fae with grep to show all processes that you are executing# with the
exception of the ps -fae and grep commands.
12. 4tart a sleep >$$ process running in the 'ackground. Log off the server# and log
'ack in again. List all the processes that you are running. What happened to your
sleep process) ow repeat# except this time start 'y running nohup sleep >$$.
13. 1ultiple 5o's can 'e issued from the same command line using the operators ?# ;;
and ||. -ry com'ining the commands cat none/istent and echo hello using each
of these operators. <everse the order of the commands and try again. What are the
rules a'out when the commands will 'e executed)
14. What does the /args command do) *an you com'ine it with find and grep to find
yet another way of searching all files in the -home su'directory tree for the word
15. What does the cut command do) *an you use it together with w to produce a list
of login names and *>U times corresponding to each active process) *an you
now (all on the same command line) use sort and head or tail to find the user
whose process is using the most *>U)
1. Use telnet to re%uest a we' page from the we' server www,doc,ic,ac,uk 'y
connecting to port 0?# as shown in the notes.
2. Use ping to find the round+trip delay to www,alta"ista,com.
3. Use traceroute to see the network route taken to www,alta"ista,com (which is in
the U4$). *an you tell which cities your network traffic passes through)
4. Use ftp to connect to the @-> site sunsite,doc,ic,ac,uk. ;'tain the latest
version of the package units (in the form of a ,tar,g8 file) from the directory
packages-gnu-units. /ecompress and unarchive the ,tar,g8 file. -ype configure
and then make. <un the executa'le program that is produced as 2,-units -f
units,dat2. What does the program do) !f you were the system administrator#
what would you have to do to install the package for everyone to use)
5. Use wget to get a copy of the we' page http@--www,doc,ic,ac,uk-inde/,html.
3ave a look at the contents of the file. *an you use sed to strip out the
3-1L tags (text enclosed in A and 3) to leave you with 5ust plain text)
6. Use finger or who to get a list of users on the machine.
7. Use write to send them a message. -o stop people from sending you messages#
type 2mesg n2. -o reena'le messages# type 2mesg !2.
8. -ry use talk to send a message to someone (.:. this may not work).
9. List all your processes# using sed to su'stitute 2me2 for your username.
10. Use who# awk# sort and uniq to print out a sorted list of the logins of active users.
11. Use awk on -etc-passwd to produce a list of users and their login shells.
12. Write an awk script that prints out all lines in a file except for the first two.
9,. 1odify the awk script in the notes so that it doesn&t increase the num'er of
players used to calculate the average if the manner of dismissal is 2not+out2.
14. *reate a file called hello,c containing the simple 2hello world2 program in the
notes. *reate an appropriate makefile for compiling it. <un make.
15. Use man -k to find a suita'le utility for viewing postscript files.
1. *opy the file mole,t/t into your home directory (press shift and the left mouse
'utton to download the file using etscape).
2. Edit your copy of the document using "i.
3. Ao to the end of the document and type in the following paragraph(
Boined the li)rar!, Cot Dare of the Skin, Erigin of the Species, and a
)ook )! a woman m! mother is alwa!s going on a)out, Ft is called Gride and
Gre<udice, )! a woman called Bane 9usten, F could tell the li)rarian was
impressed, Gerhaps she is an intellectual like me, She didnHt look at m!
spot, so perhaps it is getting smaller,
4. *orrect the three spelling errors in the first three lines of the first paragraph (one
error per line) and remove the extra 2Ceograph!2 in the ,rd line of the first
5. $dd the words 29)out timeI2 to the end of the second paragraph.
6. /elete the sentence 2Jime flies like an arrow )ut fruit flies like a
)anana2 and re+form the paragraph.
7. <eplace all occurrences of 2is2 with 2was2.
0. 4wap the two paragraphs.
B. 4ave the file and %uit.
10. <epeat the exercise with emacs. Which did you find easier)
11. *an you write a simple * program (say the hello world program) and makefile#
compile and run it + all from inside emacs)
12. !f you&d like an indepth "i tutorial try running 2"imtutor2. @or an indepth emacs
tutorial# type K-/ help-with-tutorial from inside emacs.
Lednesda! Banuar! &+th
Mone of the teechers at school ha"e noticed that F am an intellectual, Jhe!
will )e sorr! when F am famouse, Jhere is a new girl in our class, She sits
ni/t to me in Ceograph! Ceograph!,
Jime flies like an arrow )ut fruit flies like a )anana,
She is all right, Her name is Gandora, )ut she likes )eing called No/,
OonHt ask me wh!, F might fall in lo"e with her, FtHs time F fell in lo"e,
after all F am &> >-+ !ears old,
.:. >lease perform these tasks on your home >* and take extra care when using the root
account. 4ince your commands will 'e carried out without the safeguards that apply to ordinary
users# you may do serious damage to the system. !f in dou't# please ask (prefera'ly 'efore
pressing 6)
1. Use su - to 'ecome root.
2. $dd a new user of your choosing to the system. 4et their password. *heck that
they can log in.
3. $dd a new user group of your choosing to the system. >lace yourself (i.e. your
login# not root)# and the user that you have added in the group. *heck that you are
'oth in the new group.
C. <emove the user that you added.
5. 1ake yourself a cron 5o' that sends you a message (using write) every 9?
minutes. <emove this when you start to find it irritating.
6. /iscover how to restart the we' server httpd (or any other system daemon).
7. tin!httpd,pl is a mini+we' server written in >erl. Switch back to being a
normal user# and make a copy of tin!httpd,pl in your home directory. *hange
the port num'er on which it operates to a port of your choice (currently 0?0?# 'ut
use a different one that noone else will 'e using). *reate a pu)licPhtml directory
in your home directory and create a home page file inside it called 2inde/,html2.
ow run tin!httpd,pl in the 'ackground and use telnet (telnet machine port#
where machine is the hostname and port is the port num'er# and then issue the
3--> command CEJ - HJJG-&,$ ) or a we' 'rowser (call up
http@--machine@port) to test that your home page file is in fact 'eing served.
8. 4witch 'ack to 'eing root. $dd a line to -etc-initta) which will ensure that your
mini we'+server will respawn itself if it dies. Dill your we' server (using kill)
and see if the respawning works (init re+examines the -etc-initta) file
whenever one of its descendant processes dies so you should not have long to wait
for this to take effect). !t may 'e helpful to monitor the system messages file with
tail -f -"ar-log-messages.
1. Use your favourite U!" editor to create the simple shell script given in 4ection
0.C of the notes. <un it# and see how the contents of the script relates to the
2. Extend the script so that it generates a random secret num'er 'etween 9 and 9??
(c.f. Exercise 4heet ,# Euestion 9F) and then keeps asking the user to guess the
secret num'er until they guess correctly. -he script should give the user hints
such as 2!&m sorry your guess is too low2 or 2!&m sorry your guess is too high2.
3. Write a shell script which renames all ,t/t files as ,te/t files. -he command
)asename might help you here.
4. Write a shell script called pidof which takes a name as parameter and returns the
>!/(s) of processes with that name.
5. 4hell scripts can also include functions. @unctions are declared as(
function funcname4: {
and invoked as funcname param1 param2... -he parameters passed to the
function are accessi'le inside the function through the varia'les $&# $## etc. ow
add a usage4: function to your pidof script which prints usage instructions. *all
usage4: if the wrong num'er of parameters is passed to the script.
6. 1odify your ,)ashPprofile script so that your G9JH includes the current directory
(,) and so that your environment varia'le EOFJE1 is set to emacs or "i (or whatever
else you prefer to use). <un the modified script using source ,)ashPprofile and
check that the changes you made have 'een applied to the current shell (type set).
Introduction to UNIX:
Lecture Eight
8.1 Objectives
-his chapter covers(
4hells and shell scripts.
4hells varia'les and the environment.
4imple shell scripting
$dvanced shell scripting.
4tart+up shell scripts.
8.2 Shells and Shell Scripts
$ shell is a program which reads and executes commands for the user. 4hells also usually
provide features such 5o' control# input and output redirection and a command language for
writing shell scripts. $ shell script is simply an ordinary text file containing a series of
commands in a shell command language (5ust like a 2'atch file2 under 14+/;4).
-here are many different shells availa'le on U!" systems (e.g. sh# )ash# csh# ksh# tcsh etc.)#
and they each support a different command language. 3ere we will discuss the command
language for the :ourne shell sh since it is availa'le on almost all U!" systems (and is also
supported under )ash and ksh).
8.3 Shell Variables and the Environment
$ shell lets you define varia'les (like most programming languages). $ varia'le is a piece of
data that is given a name. ;nce you have assigned a value to a varia'le# you access its value 'y
prepending a $ to the name(
$ )o)QHhello worldH
$ echo $)o)
hello world
Garia'les created within a shell are local to that shell# so only that shell can access them. -he
set command will show you a list of all varia'les currently defined in a shell. !f you wish a
varia'le to 'e accessi'le to commands outside the shell# you can export it into the environment(
$ e/port )o)
(under csh you used seten"). -he environment is the set of varia'les that are made availa'le to
commands (including shells) when they are executed. U!" commands and programs can read
the values of environment varia'les# and ad5ust their 'ehaviour accordingly. @or example# the
environment varia'le G9CE1 is used 'y the man command (and others) to see what command
should 'e used to display multiple pages. !f you say(
$ e/port G9CE1Qcat
and then try the man command (say man pwd)# the page will go flying past without stopping. !f
you now say(
$ e/port G9CE1Qmore
normal service should 'e resumed (since now more will 'e used to display the pages one at a
time). $nother environment varia'le that is commonly used is the EOFJE1 varia'le which
specifies the default editor to use (so you can set this to "i or emacs or which ever other editor
you prefer). -o find out which environment varia'les are used 'y a particular command#
consult the man pages for that command.
$nother interesting environment varia'le is GS&# the main shell prompt string which you can
use to create your own custom prompt. @or example(
$ e/port GS&Q4Rh: Rw3
4lum)er<ack: .3
-he shell often incorporates efficient mechanisms for specifying common parts of the shell
prompt (e.g. in )ash you can use Rh for the current host# Rw for the current working directory# Rd
for the date# Rt for the time# Ru for the current user and so on + see the )ash man page).
$nother important environment varia'le is G9JH. G9JH is a list of directories that the shell uses
to locate executa'le files for commands. 4o if the G9JH is set to(
and you typed ls# the shell would look for -)in-ls# -usr-)in-ls etc. ote that the G9JH
contains&,&# i.e. the current working directory. -his allows you to create a shell script or
program and run it as a command from your current directory without having to explicitly say
ote that G9JH has nothing to with filenames that are specified as arguments to commands (e.g.
cat m!file,t/t would only look for ,-m!file,t/t# not for -)in-m!file,t/t#
-usr-)in-m!file,t/t etc.)
8.4 Simple Shell Scripting
*onsider the following simple shell script# which has 'een created (using an editor) in a text
file called simple(
0 this is a comment
echo Jhe num)er of arguments is $0
echo Jhe arguments are $S
echo Jhe first is $&
echo K! process num)er is $$
echo Enter a num)er from the ke!)oard@
read num)er
echo Jhe num)er !ou entered was $num)er
-he shell script 'egins with the line 20I-)in-sh2 . Usually 202 denotes the start of a comment#
'ut 0I is a special com'ination that tells U!" to use the :ourne shell (sh) to interpret this
script. -he 0I must 'e the first two characters of the script. -he arguments passed to the script
can 'e accessed through $&# $## $> etc. $S stands for all the arguments# and $0 for the num'er of
arguments. -he process num'er of the shell executing the script is given 'y $$. the read
num'er statement assigns key'oard input to the varia'le num)er.
-o execute this script# we first have to make the file simple executa'le(
$ ls -l simple
-rw-r--r-- & will finance &'( Oec &> simple
$ chmod */ simple
$ ls -l simple
-rw/r-/r-/ & will finance &'( Oec &> simple
$ ,-simple hello world
Jhe num)er of arguments is #
Jhe arguments are hello world
Jhe first is hello
K! process num)er is #==%
Enter a num)er from the ke!)oard@
Jhe num)er !ou entered was (
We can use input and output redirection in the normal way with scripts# so(
$ echo ( | simple hello world
would produce similar output 'ut would not pause to read a num'er from the key'oard.
8.5 More dvanced Shell Scripting
if-then-else statements
4hell scripts are a'le to perform simple conditional 'ranches(
if 6 test 7
-he test condition may involve file characteristics or simple string or numerical
comparisons. -he 6 used here is actually the name of a command (-)in-6) which
performs the evaluation of the test condition. -herefore there must 'e spaces
'efore and after it as well as 'efore the closing 'racket. 4ome common test
conditions are(
-s file
true if file exists and is not empty
-f file
true if file is an ordinary file
-d file
true if file is a directory
-r file
true if file is reada'le
-w file
true if file is writa'le
-/ file
true if file is executa'le
$T -eq $U
true if T e%uals U
$T -ne $U
true if T not e%ual to U
$T -lt $U
true if T less than $U
$T -gt $U
true if " greater than $U
$T -le $U
true if T less than or e%ual to U
$T -ge $U
true if T greater than or e%ual to U
$9 Q $N
true if string 9 e%uals string N
$9 IQ $N
true if string 9 not e%ual to string N
$T I -gt $U
true if string T is not greater than U
$E -a $2
true if expressions E and 2 are 'oth true
$E -o $2
true if either expression E or expression 2 is true

for loops
4ometimes we want to loop through a list of files# executing some commands on
each file. We can do this 'y using a for loop(
for variable in list
statements (referring to $variable)
-he following script sorts each text files in the current directory@
for f in S,t/t
echo sorting file $f
cat $f | sort 3 $f,sorted
echo sorted file has )een output to $f,sorted

while loops
$nother form of loop is the while loop(
while 6 test 7
statements (to 'e executed while test is true)
-he following script waits until a non+empty file input,t/t has 'een created(
while 6 I -s input,t/t 7
echo waiting,,,
sleep (
echo input,t/t is read!
7ou can a'ort a shell script at any point using the e/it statement# so the following
script is e%uivalent(
while true
if 6 -s input,t/t 7
echo input,t/t is read!
echo waiting,,,
sleep (

case statements
case statements are a convenient way to perform multiway 'ranches where one
input pattern must 'e compared to several alternatives(
case variable in
statement (executed if variable matches pattern1)
-he following script uses a case statement to have a guess at the type of non+
directory non+executa'le files passed as arguments on the 'asis of their extensions
(note how the 2or2 operator | can 'e used to denote multiple patterns# how 2S2 has
'een used as a catch+all# and the effect of the forward single %uotes V)(
for f in $S
if 6 -f $f -a I -/ $f 7
case $f in
echo $f@ a core dump file
echo $f@ a D program
echo $f@ a D** program
echo $f@ a te/t file
echo $f@ a GE1L script
echo $f@ a we) document
echo $f@ appears to )e Vfile -) $fV

capturing command output
$ny U!" command or program can 'e executed from a shell script 5ust as if you
would on the line command line. 7ou can also capture the output of a command
and assign it to a varia'le 'y using the forward single %uotes V V(
linesQVwc -l $&V
echo the file $& has $lines lines
-his script outputs the num'er of lines in the file passed as the first parameter.

arithmetic operations
-he :ourne shell doesn&t have any 'uilt+in a'ility to evaluate simple mathematical
expressions. @ortunately the U!" e/pr command is availa'le to do this. !t is
fre%uently used in shell scripts with forward single %uotes to update the value of a
varia'le. @or example(
lines Q Ve/pr $lines * &V
adds 9 to the varia'le lines. e/pr supports the operators *# -# S# -# W (remainder)#
A# AQ# Q# IQ# 3Q# 3# | (or) and ; (and).
8.! Start"#p Shell Scripts
When you first login to a shell# your shell runs a systemwide start+up script (usually called
-etc-profile under sh# )ash and ksh and -etc-,login under csh). !t then looks in your home
directory and runs your personal start+up script (,profile under sh# )ash and ksh and ,cshrc
under csh and tcsh). 7our personal start+up script is therefore usually a good place to set up
environment varia'les such as G9JH# EOFJE1 etc. @or example with )ash# to add the directory
.-)in to your G9JH# you can include the line(
e/port G9JHQ$G9JH@.-)in
in your ,profile. !f you su'se%uently modify your ,profile and you wish to import the
changes into your current shell# type(
$ source ,profile
$ , ,-profile
-he source command is 'uilt into the shell. !t ensures that changes to the environment made in
,profile affect the current shell# and not the shell that would otherwise 'e created to execute
the ,profile script.
With csh# to add the directory .-)in to your G9JH# you can include the line(
set path Q 4 $G9JH $HEKE-)in :
in your ,cshrc.
(:$*D -; *;U<4E *;-E-4)
September 2001 William Knottenbelt (wjk@doc.ic.ac.uk)