OS Lab Manual
OS Lab Manual
Lab Manual
Department of IT and Engineering
Course Name: Operating Systems
Instructor Name: Farhan Sohail, Naveed Ahmad
Operating Systems
Faculty of IT/Engineering
National University of Modern Languages Islamabad
Page - 2 -
Operating Systems
Page - 3 -
Operating Systems
Table of Contents
Lab No. 1 ____________________________________________________________ 5
Lab No. 2 ___________________________________________________________ 10
Lab No. 3 ___________________________________________________________ 18
Lab No. 4 ___________________________________________________________ 30
Lab No. 5 ___________________________________________________________ 42
Lab No. 6 ___________________________________________________________ 51
Lab No. 7 ___________________________________________________________ 59
Lab No. 8 ___________________________________________________________ 64
Lab No. 9 ___________________________________________________________ 67
Lab No. 10 __________________________________________________________ 70
Lab No. 11 __________________________________________________________ 77
Lab No. 12 __________________________________________________________ 80
Lab No. 13 __________________________________________________________ 84
Lab No. 14 __________________________________________________________ 91
Advance Topics ____________________________________________________ 118
Page - 4 -
Operating Systems
Lab No. 1
1.2- Introduction
In recent years Linux has become a phenomenon. Hardly a day goes by
without Linux cropping up in the media in some way. We’ve lost count of
the number of applications that have been made available on Linux and
the number of organizations that have adopted it, including some
government departments and city administrations.
Major hardware vendors like IBM and Dell now support Linux, and major
software vendors like Oracle support their software running on Linux. Linux
truly has become a viable operating system, especially in the server market.
Linux owes its success to systems and applications that preceded it: UNIX
and GNU software.
Page - 5 -
Operating Systems
¾ Simplicity
Page - 6 -
Operating Systems
o Many of the most useful UNIX utilities are very simple and, as a
result, small and easy to understand.
¾ Small components
o Each component should perform a single task
o Multiple components can be combined and chained
together for more complex tasks
o An individual component can be substituted for another,
without affecting other components
Page - 7 -
Operating Systems
1.5- Installation
Page - 8 -
Operating Systems
1.6- Exercise
a. What is the file system used by the Linux?
b. Name two types of boot loaders available.
c. What are the names of partitions created for Linux?
Page - 9 -
Operating Systems
Lab No. 2
2.1- Lab objective
This lab introduces few of the basic commands of Linux.
Page - 10 -
Operating Systems
Page - 11 -
Operating Systems
2.2.5 Files
¾ Data can be stored in a file
¾ Each file has a filename
o A label referring to a particular file
o Permitted characters include letters, digits, hyphens (-),
underscores (_), and dots (.)
o Case-sensitive — NewsCrew.mov is a different file from
NewScrew.mov
¾ The ls command lists the names of files
Page - 12 -
Operating Systems
Page - 13 -
Operating Systems
Page - 14 -
Operating Systems
Page - 15 -
Operating Systems
2.4- Exercises
Q1
a. Log in.
b. Log out.
c. Log in again. Open a terminal window, to start a shell.
d. Exit from the shell; the terminal window will close.
e. Start another shell. Enter each of the following commands in turn.
i. date
ii. whoami
iii. hostname
iv. uname
v. uptime
Q2
a. Use the ls command to see if you have any files.
b. Create a new file using the cat command as follows:
$ cat > hello.txt
Hello world!
This is a text file.
c. Press Enter at the end of the last line, then Ctrl+D to denote the end
of the file.
d. Use ls again to verify that the new file exists.
e. Display the contents of the file.
f. Display the file again, but use the cursor keys to execute the same
command again without having to retype it.
Q3
a. Create a second file. Call it secret-of-the-universe, and put in
whatever content you deem appropriate.
Page - 16 -
Operating Systems
Q4
After each of the following steps, use ls and cat to verify what has
happened.
a. Copy secret-of-the-universe to a new file called answer.txt. Use Tab
to avoid typing the existing file’s name in full.
b. Now copy hello.txt to answer.txt. What’s happened now?
c. Delete the original file, hello.txt.
d. Rename answer.txt to message.
e. Try asking rm to delete a file called missing. What happens?
f. Try copying secret-of-the-universe again, but don’t specify a
filename to which to copy. What happens now?
Page - 17 -
Operating Systems
Lab No. 3
3.1- Lab objective
In this lab, you will explore the Linux file system, including the basic
concepts of files and directories and their organization in a hierarchical
tree structure.
3.2.0- Background
Page - 18 -
Operating Systems
Page - 19 -
Operating Systems
$ rm -r OldAccounts
¾ Be careful — rm can be a dangerous tool if misused
3.3.4 Relative Paths
¾ Paths don’t have to start from the root directory
o A path which doesn’t start with / is a relative path
o It is relative to some other directory, usually the current
directory
¾ For example, the following sets of directory changes both end up in
the same directory:
$ cd /usr/share/doc
$ cd /
$ cd usr
$ cd share/doc
¾ Relative paths specify files inside directories in the same way as
absolute ones
Page - 20 -
Operating Systems
Page - 21 -
Operating Systems
Page - 22 -
Operating Systems
Page - 23 -
Operating Systems
Page - 24 -
Operating Systems
Page - 25 -
Operating Systems
Page - 26 -
Operating Systems
3.4- Exercises
Q1
a. Use the pwd command to find out what directory you are in.
b. If you are not in your home directory (/home/USERNAME) then use
cd without any arguments to go there, and do pwd again.
c. Use cd to visit the root directory, and list the files there. You should
see home among the list.
d. Change into the directory called home and again list the files
present. There should be one directory for each user, including the
user you are logged in as (you can use whoami to check that).
e. Change into your home directory to confirm that you have gotten
back to where you started.
Q2
a. Create a text file in your home directory called shakespeare,
containing the following text:
Shall I compare thee to a summer’s day?
Thou art more lovely and more temperate
b. Rename it to sonnet-18.txt.
c. Make a new directory in your home directory, called poetry.
d. Move the poem file into the new directory.
e. Try to find a graphical directory-browsing program, and find your
home directory with it. You should also be able to use it to explore
some of the system directories.
f. Find a text editor program and use it to display and edit the sonnet.
Page - 27 -
Operating Systems
Q3
a. From your home directory, list the files in the directory /usr/share.
b. Change to that directory, and use pwd to check that you are in the
right place. List the files in the current directory again, and then list
the files in the directory called doc.
c. Next list the files in the parent directory, and the directory above
that.
d. Try the following command, and make sure you understand the
result:
$ echo ˜
e. Use cat to display the contents of a text file which resides in your
home directory (create one if you haven’t already), using the ˜/
syntax to refer to it. It shouldn’t matter what your current directory is
when you run the command.
Q4
a. Use the hostname command, with no options, to print the
hostname of the machine you are using.
b. Use man to display some documentation on the hostname
command. Find out how to make it print the IP address of the
machine instead of the hostname. You will need to scroll down the
manpage to the ‘Options’ section.
c. Use the locate command to find files whose name contains the text
‘hostname’. Which of the filenames printed contain the actual
hostname program itself? Try running it by entering the program’s
absolute path to check that you really have found it.
Page - 28 -
Operating Systems
Q5
a. The * wildcard on its own is expanded by the shell to a list of all the
files in the current directory. Use the echo command to see the
result (but make sure you are in a directory with a few files or
directories first)
b. Use quoting to make echo print out an actual * symbol.
c. Augment the poetry directory you created earlier with another file,
sonnet-29.txt:
When in disgrace with Fortune and men’s eyes,
I all alone beweep my outcast state,
d. Use the cat command to display both of the poems, using a
wildcard.
e. Finally, use the rm command to delete the poetry directory and the
poems in it.
Page - 29 -
Operating Systems
Lab No. 4
4.1.0- Lab objective
This lab will give overview of Linux shells. You will get insight of ‘bash’ shell.
4.1.1- Background
Shells
¾ A shell provides an interface between the user and the operating
system kernel
¾ Either a command interpreter or a graphical user interface
¾ Traditional Unix shells are command-line interfaces (CLIs)
¾ Usually started automatically when you log in or open a terminal
Page - 30 -
Operating Systems
Page - 31 -
Operating Systems
¾ The options usually come first, but for most commands they do not
need to
¾ There is a special option ‘--’ which indicates the end of the options
o Nothing after the double hyphen is treated as an option,
even if it starts with -
Page - 32 -
Operating Systems
$ ls -la
4.2.6 Setting Shell Variables
¾ Shell variables can be used to store temporary values
¾ Set a shell variable’s value as follows:
$ files="notes.txt report.txt"
o The double quotes are needed because the value contains a
space
o Easiest to put them in all the time
¾ Print out the value of a shell variable with the echo command:
$ echo $files
o The dollar ($) tells the shell to insert the variable’s value into
the command line
¾ Use the set command (with no arguments) to list all the shell
variables
Page - 33 -
Operating Systems
Page - 34 -
Operating Systems
Page - 35 -
Operating Systems
Page - 36 -
Operating Systems
Page - 37 -
Operating Systems
Page - 38 -
Operating Systems
Page - 39 -
Operating Systems
4.3- Exercises
Q1
a. Use the df command to display the amount of used and
available space on your hard drive.
b. Check the man page for df, and use it to find an option to the
command which will display the free space in a more human-
friendly form. Try both the single-letter and long-style options.
c. Run the shell, bash, and see what happens. Remember that you
were already running it to start with. Try leaving the shell you
have started with the exit command.
Q2
a. Try ls with the -a and -A options. What is the difference between
them?
b. Write a for loop which goes through all the files in a directory and
prints out their names with echo. If you write the whole thing on
one line, then it will be easy to repeat it using the command line
history.
c. Change the loop so that it goes through the names of the
people in the room (which needn’t be the names of files) and
print greetings to them.
d. Of course, a simpler way to print a list of filenames is echo *. Why
might this be useful, when we usually use the ls command?
Page - 40 -
Operating Systems
Q3
a. Use the find command to list all the files and directories under
your home directory. Try the -type d and -type f criteria to show
just files and just directories.
b. Use ‘locate’ to find files whose name contains the string
‘bashbug’. Try the same search with find, looking over all files on
the system. You’ll need to use the * wildcard at the end of the
pattern to match files with extensions.
c. Find out what the find criterion -iname does.
Page - 41 -
Operating Systems
Lab No. 5
5.1.0- Lab objective
This lab will give overview of Basic File and Directory Management utilities.
Page - 42 -
Operating Systems
Page - 43 -
Operating Systems
Page - 44 -
Operating Systems
5.5.1 Examples of cp
¾ Copy /etc/smb.conf to the current directory:
$ cp /etc/smb.conf .
¾ Create an identical copy of a directory called work, and call it
work-backup:
$ cp -a work work-backup
¾ Copy all the GIF and JPEG images in the current directory into
images:
$ cp *.gif *.jpeg images/
Page - 45 -
Operating Systems
Page - 46 -
Operating Systems
Page - 47 -
Operating Systems
Page - 48 -
Operating Systems
5.10 Exercises
Q1
a. Use cd to go to your home directory, and create a new directory there
called dog.
b. Create another directory within that one called cat, and another within
that called mouse.
c. Remove all three directories. You can either remove them one at a
time, or all at once.
d. If you can delete directories with rm -r, what is the point of using rmdir
for empty directories?
e. Try creating the dog/cat/mouse directory structure with a single
command.
Q2
a. Copy the file /etc/passwd to your home directory, and then use cat to
see what’s in it.
b. Rename it to users using the mv command.
c. Make a directory called programs and copy everything from /bin into
it.
d. Delete all the files in the programs directory.
e. Delete the empty programs directory and the users file.
Q3
a. The touch command can be used to create new empty files. Try that
now, picking a name for the new
file:
$ touch baked-beans
b. Get details about the file using the ls command:
$ ls -l baked-beans
c. Wait for a minute, and then try the previous two steps again, and see
what changes. What happens
Page - 49 -
Operating Systems
Page - 50 -
Operating Systems
Lab No. 6
6.1.0- Lab objective
This lab will give overview of Processing Text Streams using Text Processing
Filters
Page - 51 -
Operating Systems
Page - 52 -
Operating Systems
o Default is –clw
¾ Examples: display word count for essay.txt:
$ wc -w essay.txt
¾ Display the total number of lines in several text files:
$ wc -l *.txt
6.5 Sorting Lines of Text with sort
¾ The sort filter reads lines of text and prints them sorted into order
¾ For example, to sort a list of words into dictionary order:
$ sort words > sorted-words
¾ The -f option makes the sorting case-insensitive
¾ The -n option sorts numerically, rather than lexicographically
6.6 Removing Duplicate Lines with uniq
¾ Use uniq to find unique lines in a file
¾ Removes consecutive duplicate lines
¾ Usually give it sorted input, to remove all duplicates
o Example: find out how many unique words are in a dictionary:
$ sort /usr/dict/words | uniq | wc –w
¾ sort has a -u option to do this, without using a separate program:
$ sort -u /usr/dict/words | wc -w
¾ sort | uniq can do more than sort -u, though:
¾ uniq -c counts how many times each line appeared
¾ uniq -u prints only unique lines
¾ uniq -d prints only duplicated lines
6.7 Selecting Parts of Lines with cut
¾ Used to select columns or fields from each line of input
¾ Select a range of
o Characters, with
o Fields, with –f
o Field separator specified with -d (defaults to tab)
Page - 53 -
Operating Systems
Page - 54 -
Operating Systems
Page - 55 -
Operating Systems
Page - 56 -
Operating Systems
6.16 Exercises
Q1
a. Type in the example on the cut slide to display a list of users logged in.
(Try just who on its own first to see what is happening.)
b. Arrange for the list of usernames in who’s output to be sorted, and
remove any duplicates.
c. Try the command last to display a record of login sessions, and then try
reversing it with tac. Which is more useful? What if you pipe the output into
less?
d. Use sed to correct the misspelling ‘enviroment’ to ‘environment’. Use it
on a test file, containing a few lines of text, to check it. Does it work if the
misspelling occurs more than once on the same line?
e. Use nl to number the lines in the output of the previous question.
Q2
a. Try making an empty file and using tail -f to monitor it. Then add lines to
it from a different terminal using a command like this:
$ echo "testing" >>filename
b. Once you have written some lines into your file, use tr to display it with
all occurances of the letters A–F changed to the numbers 0–5.
c. Try looking at the binary for the ls command (/bin/ls) with less. You can
use the -f option to force it to display the file, even though it isn’t text.
d. Try viewing the same binary with od. Try it in its default mode, as well as
with the options shown on the slide for outputting in hexadecimal.
Q3
a. Use the split command to split the binary of the ls command into 1Kb
chunks. You might want to create a directory especially for the split files,
so that it can all be easily deleted later.
Page - 57 -
Operating Systems
b. Put your split ls command back together again, and run it to make sure
it still works. You will have to make sure you are running the new copy of it,
for example ./my_ls, and make sure that the program is marked as
‘executable’ to run it, with the following command:
$ chmod a+rx my_ls
Page - 58 -
Operating Systems
Lab No. 7
7.1.0- Lab objective
This lab will give overview of the use of Unix Streams, Pipes and Redirects.
Page - 59 -
Operating Systems
7.2 Pipes
¾ A pipe channels the output of one program to the input of another
¾ Allows programs to be chained together
¾ Programs in the chain run concurrently
¾ Use the vertical bar: |
¾ Sometimes known as the ‘pipe’ character
¾ Programs don’t need to do anything special to use pipes
¾ They read from stdin and write to stdout as normal
¾ For example, pipe the output of echo into the program rev (which
reverses each line of its input):
$ echo Happy Birthday! | rev
!yadhtriB yppaH
Page - 60 -
Operating Systems
Page - 61 -
Operating Systems
7.3.4 tee
¾ The tee program makes a ‘T-junction’ in a pipeline
¾ It copies data from stdin to stdout, and also to a file
¾ Like > and | combined
¾ For example, to save details of everyone’s logins, and save Bob’s
logins in a separate file:
$ last | tee everyone.txt | grep bob > bob.txt
Page - 62 -
Operating Systems
7.4 Exercises
Q1
a. Try the example on the ‘Pipes’ slide, using rev to reverse some text.
b. Try replacing the echo command with some other commands which
produce output (e.g., whoami).
c. What happens when you replace rev with cat? You might like to try
running cat with no arguments and entering some text.
Q2
a. Run the command ls --color in a directory with a few files and
directories. Some Linux distributions have ls set up to always use the --color
option in normal circumstances, but in this case we will give it explicitly.
b. Try running the same command, but pipe the output into another
program (e.g., cat or less). You should spot two differences in the output.
ls detects whether its output is going straight to a terminal (to be viewed
by a human directly) or into a pipe (to be read by another program).
Page - 63 -
Operating Systems
Lab No. 8
8.1.0- Lab objective
This lab will give overview the use of Regular Expressions for searching test
files.
Page - 64 -
Operating Systems
Page - 65 -
Operating Systems
8.3 Exercises
Q1
a. Use grep to find information about the HTTP protocol in the file
/etc/services.
b. Usually this file contains some comments, starting with the ‘#’ symbol.
Use grep with the -v option to ignore lines starting with ‘#’ and look at the
rest of the file in less.
c. Add another use of grep -v to your pipeline to remove blank lines
(which match the pattern ˆ$).
d. Use sed (also in the same pipeline) to remove the information after the
‘/’ symbol on each line, leaving just the names of the protocols and their
port numbers.
Page - 66 -
Operating Systems
Lab No. 9
9.1.0- Lab objective
This lab will give overview of Job Control.
¾ Most shells offer job control
¾ The ability to stop, restart, and background a running process
¾ The shell lets you put & on the end of a command line to start it in
the background
¾ Or you can hit Ctrl+Z to suspend a running foreground job
¾ Suspended and backgrounded jobs are given numbers by the shell
¾ These numbers can be given to shell job-control built-in commands
¾ Job-control commands include jobs, fg, and bg
9.2 jobs
¾ The jobs builtin prints a listing of active jobs and their job numbers:
$ jobs
[1]- Stopped vim index.html
[2] Running netscape &
3]+ Stopped man ls
¾ Job numbers are given in square brackets
o But when you use them with other job-control builtins, you
need to write them with percent signs, for example %1
o The jobs marked + and - may be accessed as %+ or %- as well
as by number
o %+ is the shell’s idea of the current job — the most recently
active job
o %- is the previous current job
Page - 67 -
Operating Systems
9.3 fg
¾ Brings a backgrounded job into the foreground
¾ Re-starts a suspended job, running it in the foreground
o fg %1 will foreground job number 1
o fg with no arguments will operate on the current job
9.4 bg
¾ Re-starts a suspended job, running it in the background
¾ bg %1 will background job number 1
¾ bg with no arguments will operate on the current job
o For example, after running gv and suspending it with Ctrl+Z,
use bg to start it running again in the background.
Page - 68 -
Operating Systems
9.5 Exercises
Q1
a. Start a process by running man bash and suspend it with Ctrl+Z.
o Run process in the background, using &.
o Use jobs to list the backgrounded and stopped processes.
o Use the fg command to bring man into the foreground, and
quit from it as normal.
o Use fg to foreground the process, and terminate it with
Ctrl+C.
o Run the process again, but this time without &. It should be
running in the foreground (so you can’t use the shell). Try
suspending it with Ctrl+Z and see what happens. To properly
put it into the background, use bg.
Page - 69 -
Operating Systems
Lab No. 10
10.1.0- Lab objective
This lab will involve Creating, Monitoring, and Killing Processes.
Page - 70 -
Operating Systems
10.2.1 ps Options
¾ ps has many options
¾ Some of the most commonly used are:
¾ Option Description
Page - 71 -
Operating Systems
Page - 72 -
Operating Systems
Page - 73 -
Operating Systems
o k Prompts for a pid and a signal, and sends that signal to that
process
o n Prompts for the number of processes to show information; 0
(the default) means to show as many as will fit
o r Change the priority (‘niceness’) of a process
o s Change the number of seconds to delay between updates.
The number may include fractions of a second (0.5, for
example)
Page - 74 -
Operating Systems
Page - 75 -
Operating Systems
10.5 Exercises
Q1
a. Use top to show the processes running on your machine.
b. Make top sort by memory usage, so that the most memory-hungry
processes appear at the top.
c. Restrict the display to show only processes owned by you.
d. Try killing one of your processes (make sure it’s nothing important).
e. Display a list of all the processes running on the machine using ps
(displaying the full command line for them).
f. Get the same listing as a tree, using both ps and pstree.
g. Have ps sort the output by system time used.
Page - 76 -
Operating Systems
Lab No. 11
11.1.0- Lab objective
This lab will concentrate on Modifying Process Execution Priorities.
11.1 Concepts
¾ Not all tasks require the same amount of execution time
¾ Linux has the concept of execution priority to deal with this
¾ Process priority is dynamically altered by the kernel
¾ You can view the current priority by looking at top or ps -l and
looking at the PRI column
¾ The priority can be biased using nice
¾ The current bias can be seen in the NI column in top
11.2.0 nice
¾ Starts a program with a given priority bias
¾ Peculiar name: ‘nicer’ processes require fewer resources
¾ Niceness ranges from +19 (very nice) to -20 (not very nice)
¾ Non-root users can only specify values from 1 to 19; the root user
can specify the full range of values
¾ Default niceness when using nice is 10
¾ To run a command at increased niceness (lower priority):
$ nice -10 long-running-command &
$ nice -n 10 long-running-command &
¾ To run a command at decreased niceness (higher priority):
$ nice --15 important-command &
$ nice -n -15 important-command &
Page - 77 -
Operating Systems
11.2.1 renice
¾ renice changes the niceness of existing processes
¾ Non-root users are only permitted to increase a process’s niceness
¾ To set the process with pid 2984 to the maximum niceness (lower
priority):
$ renice 20 2984
¾ The niceness is just a number: no extra - sign
¾ To set the process with pid 3598 to a lower niceness (higher priority):
$ renice -15 3598
¾ You can also change the niceness of all a user’s processes:
$ renice 15 -u mikeb
Page - 78 -
Operating Systems
11.3 Exercises
Q1
a. Create the following shell script, called forever, in your home directory:
#!/bin/sh
while [ 1 ]; do
echo hello... >/dev/null;
done
Make it executable and run it in the background as follows:
$ chmod a+rx forever
$ ./forever &
Page - 79 -
Operating Systems
Lab No. 12
12.1.0- Lab objective
This lab will concentrate on Managing File Ownership.
Page - 80 -
Operating Systems
$ whoami
fred
$ su -
Password:
# whoami
root
67
Page - 81 -
Operating Systems
Page - 82 -
Operating Systems
12.4 Exercises
Q1
a. Find out who owns the file /bin/ls and who owns your home directory (in
/home).
b. Log on as root, and create an empty file with touch. The user and
group owners should be ‘root’ — check with ls.
c. Change the owner of the file to be ‘users’.
d. Change the group owner to be any non-root user.
e. Change both of the owners back to being ‘root’ with a single
command.
Page - 83 -
Operating Systems
Lab No. 13
13.1.0- Lab objective
This lab will give insight to Use of File Permissions to Control Access to Files.
Page - 84 -
Operating Systems
Page - 85 -
Operating Systems
$ cp -p important.txt important.txt.orig
¾ Alternatively, the -a option preserves all information possible,
including permissions and timestamps
Page - 86 -
Operating Systems
Page - 87 -
Operating Systems
Page - 88 -
Operating Systems
Page - 89 -
Operating Systems
13.11 Exercises
Q1
a. Find out what permissions are set on your home directory (as a normal
user). Can other users access files inside it?
b. If your home directory is only accessible to you, then change the
permissions to allow other people to read files inside it, otherwise change
it so that they can’t.
c. Check the permissions on /bin and /bin/ls and satisfy yourself that they
are reasonable.
d. Check the permissions available on /etc/passwd and /etc/shadow.
e. Write one command which would allow people to browse through your
home directory and any subdirectories inside it and read all the files.
Page - 90 -
Operating Systems
Lab No. 14
14.1.0- Lab objective
This lab will give an overview of The Shell as a Programming Language
14.1.1- Background
Shells
¾ A shell provides an interface between the user and the operating
system kernel
¾ Either a command interpreter or a graphical user interface
¾ Traditional Unix shells are command-line interfaces (CLIs)
¾ Usually started automatically when you log in or open a terminal
¾ There are two ways of writing shell programs.
o You can type a sequence of commands and allow the shell
to execute them interactively.
o Or you can store those commands in a file that you can then
invoke as a program.
Page - 91 -
Operating Systems
then
echo $file
fi
done
exit 0
Page - 92 -
Operating Systems
¾ The simpler way is to invoke the shell with the name of the script file
as a parameter:
$ /bin/sh first
¾ Do this by changing the file mode to make the file executable for
all users using the chmod command:
$ chmod +x first
or
# chmod u=rwx,go=rx /usr/local/bin/first
¾ Note that for scripts, you need both execute permission and read
permission
o The script interpreter (which runs with your permissions) needs
to be able to read the script from the file
Page - 93 -
Operating Systems
14.2.1 Variables
¾ You don’t usually declare variables in the shell before using them.
¾ Instead, you create them by simply using them (for example, when
you assign an initial value to them). By default, all variables are
considered and stored as strings, even when they are assigned
numeric values.
¾ The shell and some utilities will convert numeric strings to their values
in order to operate on them as required.
¾ Linux is a case-sensitivesystem, so the shell considers the variable foo
to be different from Foo, and both to be different from FOO.
$ salutation=Hello
$ echo $salutation
Hello
$ salutation=”Yes Dear”
$ echo $salutation
Page - 94 -
Operating Systems
Yes Dear
$ salutation=7+5
$ echo $salutation
7+5
14.2.4 Quoting
¾ Normally, parameters in scripts are separated by whitespace
characters (e.g., a space, a tab, or a newline character).
¾ If you want a parameter to contain one or more whitespace
characters, you must quote the parameter.
¾ The behavior of variables such as $foo inside quotes depends on
the type of quotes you use.
Page - 95 -
Operating Systems
Page - 96 -
Operating Systems
Page - 97 -
Operating Systems
It’s easy to see the difference between $@ and $* by trying them out:
$ IFS=’‘
$ set foo bar bam
$ echo “$@“
foo bar bam
$ echo “$*“
foobarbam
$ unset IFS
$ echo “$*“
foo bar bam
Page - 98 -
Operating Systems
Page - 99 -
Operating Systems
14.3.0 Conditions
¾ Fundamental to all programming languages is the ability to test
conditions and perform different actions based on those decisions.
¾ A shell script can test the exit code of any command that can be
invoked from the command line, including the scripts that you have
written yourself. That’s why it’s important to always include an exit
command with a value at the end of any scripts that you write.
if test -f fred.c
then
...
fi
¾ You can also write it like this:
Page - 100 -
Operating Systems
if [ -f fred.c ]
then
...
fi
¾ The test command’s exit code (whether the condition is satisfied)
determines whether the conditional code is run.
¾ Note that you must put spaces between the [ braces and the
condition being checked.
¾ You can remember this by remembering that [ is just the same as
writing test, and you would always leave a space after the test
command.
¾ If you prefer putting then on the same line as if, you must add a
semicolon to separate the test from the then :
if [ -f fred.c ]; then
...
fi
¾ The condition types that you can use with the test command fall
into three types: string comparison, arithmetic comparison, and
file conditionals.
¾ The following table describes these condition types:
Page - 101 -
Operating Systems
Page - 102 -
Operating Systems
then
echo “/bin/bash is a directory”
else
echo “/bin/bash is NOT a directory”
fi
14.4.1 if
¾ The if statement is very simple: It tests the result of a command and
then conditionally executes a group of statements:
if condition
then
statements
else
statements
fi
Page - 103 -
Operating Systems
else
echo “Good afternoon”
fi
exit 0
14.4.2 elif
¾ It allows you to add a second condition to be checked when the
else portion of the if is executed.
¾ You can modify the previous script so that it reports an error
message if the user types in anything other than yes or no. Do this by
replacing the else with elif and then adding another condition:
#!/bin/sh
echo “Is it morning? Please answer yes or no”
read timeofday
if [ $timeofday = “yes” ]
then
echo “Good morning”
elif [ $timeofday = “no” ]; then
echo “Good afternoon”
else
echo “Sorry, $timeofday not recognized. Enter yes or no”
exit 1
fi
Page - 104 -
Operating Systems
exit 0
Page - 105 -
Operating Systems
fi
exit 0
14.4.4 for
¾ Use the for construct to loop through a range of values, which can
be any set of strings.
¾ They could be simply listed in the program or, more commonly, the
result of a shell expansion of filenames.
¾ The syntax is simple:
for variable in values
do
statements
done
#!/bin/sh
for foo in bar fud 43
do
echo $foo
done
exit 0
¾ That results in the following output:
bar
fud
43
Page - 106 -
Operating Systems
#!/bin/sh
for file in $(ls f*.sh); do
lpr $file
done
exit 0
14.4.7 while
¾ Because all shell values are considered strings by default, the for
loop is good for looping through a series of strings, but is not so
useful when you don’t know in advance how many times you want
the loop to be executed.
¾ When you need to repeat a sequence of commands, but don’t
know in advance how many times they should execute, you will
normally use a while loop, which has the following syntax:
Page - 107 -
Operating Systems
while condition do
statements
done
#!/bin/sh
echo “Enter password”
read trythis
while [ “$trythis” != “secret” ]; do
echo “Sorry, try again”
read trythis
done
exit 0
¾ An example of the output from this script is as follows:
Enter password
password
Sorry, try again
secret
$
¾ Clearly, this isn’t a very secure way of asking for a password, but it
does serve to illustrate the while statement.
¾ The statements between do and done are continuously executed
until the condition is no longer true. In this case, you’re checking
whether the value of trythis is equal to secret.
Page - 108 -
Operating Systems
¾ The loop will continue until $trythis equals secret. You then continue
executing the script at the statement immediately following the
done.
¾ This means using a wildcard for the string value and letting the shell
fill out all the values at run time.
14.4.8 until
¾ The until statement has the following syntax:
until condition
do
statements
done
¾ This is very similar to the while loop, but with the condition test
reversed. In other words, the loop continues until the condition
becomes true, not while the condition is true.
14.5.0 case
¾ The case construct is a little more complex than those you have
encountered so far. Its syntax is as follows:
case variable in
pattern [ | pattern] ...) statements;;
pattern [ | pattern] ...) statements;;
...
Esac
¾ This may look a little intimidating, but the case construct enables
you to match the contents of a variable against patterns in quite a
Page - 109 -
Operating Systems
#!/bin/sh
echo “Is it morning? Please answer yes or no”
read timeofday
case “$timeofday” in
yes) echo “Good Morning”;;
no ) echo “Good Afternoon”;;
y ) echo “Good Morning”;;
n ) echo “Good Afternoon”;;
* ) echo “Sorry, answer not recognized”;;
esac
Page - 110 -
Operating Systems
exit 0
Page - 111 -
Operating Systems
Esac
exit 0
Page - 112 -
Operating Systems
14.6.0 Lists
¾ Sometimes you want to connect commands in a series.
¾ For instance, you may want several different conditions to be met
before you execute a statement:
if [ -f this_file ]; then
if [ -f that_file ]; then
if [ -f the_other_file ]; then
echo “All files present, and correct”
fi
fi
fi
¾ Although these can be implemented using multiple if statements,
you can see that the results are awkward.
¾ The shell has a special pair of constructs for dealing with lists of
commands: the AND list and the OR list.
¾ These are often used together, but we’ll review their syntax
separately.
Page - 113 -
Operating Systems
#!/bin/sh
touch file_one
rm -f file_two
if [ -f file_one ] && echo “hello” && [ -f file_two ] && echo “ there”
then
echo “in if”
else
echo “in else”
fi
exit 0
¾ Try the script and you’ll get the following result:
hello
in else
Page - 114 -
Operating Systems
¾ The || list is very similar to the && list, except that the rule for
executing the next statement is that the previous statement must
fail.
#!/bin/sh
rm -f file_one
if [ -f file_one ] || echo “hello” || echo “ there”
then
echo “in if”
else
echo “in else”
fi
exit 0
14.7.0 Functions
¾ You can define functions in the shell; and if you write shell scripts of
any size, you’ll want to use them to structure your code.
¾ To define a shell function, simply write its name followed by empty
parentheses and enclose the statements in braces:
function_name () {
statements
}
¾ Let’s look at a really simple function:
#!/bin/sh
foo() {
echo “Function foo is executing”
}
Page - 115 -
Operating Systems
script starting
Function foo is executing
script ending
Page - 116 -
Operating Systems
Page - 117 -
Operating Systems
Advance Topics
Lab No. 15(OPTIONAL TOPICS)
Page - 118 -
Operating Systems
Page - 119 -
Operating Systems
Page - 120 -
Operating Systems
Page - 121 -
Operating Systems
Page - 122 -
Operating Systems
Page - 123 -
Operating Systems
Page - 124 -
Operating Systems
Page - 125 -
Operating Systems
17.11 Exercises
Q1
a. Use mount to find out which filesystems are mounted.
b. Check the /etc/fstab file to see whether the floppy drive is configured
properly, and find out what its mount point is set to.
c. Mount a floppy disk at the default mount point.
d. Copy a file onto the floppy disk. Does Linux write it immediately?
Unmount the floppy to ensure that everything on it is properly written, and
it is safe to remove.
e. Try the commands on the last slide to mount a file, and try copying
some files into it. Try using the df command to see how much space is
available in the file. Unmount /mnt/disk as you would any other
filesystem.
Page - 126 -
Operating Systems
Page - 127 -
Operating Systems
Page - 128 -
Operating Systems
18.3.1 du Options
¾ Option Description
o -a Show all files, not just directories
Page - 129 -
Operating Systems
Page - 130 -
Operating Systems
Page - 131 -