8/17/2019 ISC 357 Lab Manual
1/132
8/17/2019 ISC 357 Lab Manual
2/132
2 | P a g e
TABLE OF CONTENTS
Lab Hardware, Software’s / Tools Requirements ............................................................................................... 6
LAB SYLLABUS for ISC357 ............................................................................................................................................ 7
Operating Systems and File System Organization .............................................................................................. 7 Course catalog ............................................................................................................................................................... 7
Lab Objective ................................................................................................................................................................. 7
Prerequisite .................................................................................................................................................................... 7
Lab Schedule .................................................................................................................................................................. 8
Evaluation Policy ......................................................................................................................................................... 9
Project .............................................................................................................................................................................. 9
Laboratory Policy ........................................................................................................................................................ 9
Laboratory 0: How install UBUNTU 8.10 DESK TOP EDITION ........................................................... 10 Laboratory1: Introduction to the UNIX Operating System .......................................................................... 18
What is UNIX? ............................................................................................................................................................. 18
Types of UNIX ............................................................................................................................................................. 18
Unix Major Components ........................................................................................................................................ 18
Files and processes .................................................................................................................................................. 19
The Directory Structure ......................................................................................................................................... 20
Accessing UNIX System .......................................................................................................................................... 21
Connected to UNIX machines remotely via Putty ....................................................... ............ 21 Starting UNIX terminal ................................................................. ..................................................... 22
Laboratory2,4: Unix Commands.............................................................................................................................. 24
Command syntax rules ........................................................................................................................................... 24
UNIX Directory Management Commands ....................................................................................................... 25
Printing working directory command - pwd ..................................................... ....................... 25
Changing Directory- cd ................................................................ ..................................................... 25
List -ls ....................................................... ................................................................. ............................... 27
Make a directory-mkdir ............................................................... ..................................................... 28
Remove directory ................................................................ ............................................................... . 29
copy -cp .............................................................. .............................................................. ....................... 30
Move-mv ................................................................................. ............................................................... . 31
Display file content- cat, more, less, head, tail ............................................................. ............ 31
Finding a file – find ............................. ................................................................. ............................... 32
Searching the Contents of a File .......................... .............................................................. ............ 33
Determine file type ................................................................................................................. ............ 34
Entering more than one command .................................................................................................................... 34
8/17/2019 ISC 357 Lab Manual
3/132
3 | P a g e
Redirecting standard input and output ........................................................................................................... 34
Access Permissions .................................................................................................................................................. 35
Understanding Access Permissions ....... ............................................................... ....................... 35
Displaying Access Permissions .......................................................................................... ............ 35
Default Access Permissions ........................................................ ..................................................... 36
Changing Access Permissions ............................................................... .......................................... 36
Process related commands ................................................................................................................................... 37
What is a Process? ............................................................... ............................................................... . 37
Monitoring processes ........................ ................................................................. ............................... 37
Managing Jobs and Processes ......................................................................................................... 38
Placing a foreground process in the background ..................................................................... 39
Miscellaneous Command ....................................................................................................................................... 40 Excersices..................................................................................................................................................................... 41
Laboratory 5, 6: Shell Programming ..................................................................................................................... 42
Overview of Shell ...................................................................................................................................................... 42
User defined variables ............................................................................................................................................ 43
Reading Values into User-defined Variables (Reading user input): ................................ 43
Command Substitution: ......................................... ............................................................... ............ 44
Computation on Shell Variables .......................................................... .......................................... 45
Pre-defined shell variables ................................................................................................................................... 45
Passing arguments to the shell .................................................................... .................................. 46
Shift command .......................................................................................................................... 46
Conditional Execution Operators ....................................................................................................................... 48
Conditional statements .......................................................................................................................................... 49
The if statement ......................................................... .............................................................. ............ 49
Nested if statement .................................................................................................................. 49
test Command ........................................................................................................................... 49
The case statement ............................................................. ............................................................... . 52
Flow of control statements ................................................................................................................................... 54
The for statement ................................................................ ............................................................... . 54
The while and until statements ................................................ ..................................................... 55
The break and continue statements .............................................................. ............................... 55
Excersices..................................................................................................................................................................... 58
Laboratory7: UNIX and Advance topics in C Programming ..................... ..................... ...................... ......... 59
A Simple C Program ................................................................................................................................................. 59
Compile and Execute a C program under Unix System ..................... ..................... ...................... ............. 59
8/17/2019 ISC 357 Lab Manual
4/132
4 | P a g e
UNIX Library Functions.......................................................................................................................................... 60
C Functions .................................................................................................................................................................. 61
Command line arguments in C ............................................................................................................................ 62
Running UNIX Commands From C ..................................................................................................................... 63
laboratory8: Major File Structure Related System Calls ............................................................................... 64
What is a System Call? ............................................................................................................................................ 64
Use of System Calls ................................................................................................................................................... 64
creat( ) System Call .................................................................................................................................................. 66
close( ) System call ................................................................................................................................................... 69
read() write()System calls .................................................................................................................................... 69
lseek() system call .................................................................................................................................................... 70
Excersices..................................................................................................................................................................... 72
laboratory9, 10: Process Creation and Execution ............................................................................................ 73
The death of a parent or child process............................................................................................................. 76
Parent process dies before child process ............................................................ ....................... 76
Child process dies before parent process ........................................................... ....................... 77
Excersices..................................................................................................................................................................... 78
Laboratory11: Inter-Process Communication: Pipes & Signals .................... ..................... ...................... .. 82
Pipes ............................................................................................................................................................................... 82
pipe System Call ......................................................... .............................................................. ............ 82
I/O with a pipe .......................................................................................................................... 83
Signals ............................................................................................................................................................................ 89
SIGHUP ......................................................................... ............................................................... ............ 90
SIGINT ...................................................... ................................................................. ............................... 90
SIGTSTP .............................................................. .............................................................. ....................... 90
SIGQUIT .............................................................. .............................................................. ....................... 90
SIGILL ....................................................... ................................................................. ............................... 91
SIGTRAP ................................................................................................................ .................................. 91 SIGIOT ...................................................... ................................................................. ............................... 91
SIGEMT ....................................................................................................... ............................................. 91
SIGFPE ................................................................ .............................................................. ....................... 91
SIGKILL ............................................................... .............................................................. ....................... 91
SIGBUS ........................................................................................................ ............................................. 91
SIGSEGV........................................................................ ............................................................... ............ 91
SIGPIPE ............................................................... .............................................................. ....................... 91
SIGALARM ................................................................................................. ............................................. 92
8/17/2019 ISC 357 Lab Manual
5/132
8/17/2019 ISC 357 Lab Manual
6/132
6 | P a g e
LAB HARDWARE, SOFTWARE’S / TOOLS REQUIREMENTS
Software’s
Currently used software
1. Redhat server
2. Putty which is a client program for the ssh, telnet and rlogin network protocols.
3. Ubuntu for DESKT OP
Hardware
Hardware required is standard PC having Mouse, Keyboard, Monitor, and Networking Support.
8/17/2019 ISC 357 Lab Manual
7/132
7 | P a g e
LAB SYLLABUS FOR ISC357
OPERATING SYSTEMS AND FILE SYSTEM ORGANIZATION
COURSE CATALOG
The main aim of this course is to acquire a systematic knowledge of operating systems and to
develop a critical understanding of their purpose, the main concepts, techniques and methods.
Topics covered include processes and threads, scheduling, memory management, file systems,
and storage file organizations and access methods from the operating system, programming
language, and information systems design perspectives are also introduced.
LAB OBJECTIVE
The objective of the operating systems labs is to practically implement the major operating
system issues discussed in the lectures. All the process, memory, file and directory management
issues will be demonstrated under the UNIX/LINUX operating system. Also the UNIX commands
and shell programming will be discussed in detail.
PREREQUISITE
It is very essential for students to have strong knowledge of the C language for this course, as all
experiments will be written in C language.
8/17/2019 ISC 357 Lab Manual
8/132
8 | P a g e
LAB SCHEDULE
Lab Topic
Lab-1 Introduction get familiar with UNIX,
Connect to UNIX machines remotely via Putty,
Starting UNIX terminal (UBUNTU),
Getting user accounts, and How to Login Redhat server,
Getting familiar with UNIX environment.
Lab-2 Unix Directory Management Commands (pwd, cd, ls, mkdir, rmdir, cp, mv, find, Determinefile type: file, Linking files and directories)
Lab-3 File Manipulation Commands
Display file content ( cat, more, less, head, tail)
Searching the Contents of a File : grep
Sorting the content of a file
File Manipulation Commands: vi Text Editors
Lab-4 Continue Unix Commands
Entering more than one command.
Redirecting standard input and output.
Miscellaneous Command (who, finger, echo, tty ,Id , Clear, Hostname, cal, wc)
Access Permissions command.
Lab-5, 6 UNIX Shell Programming
Lab-7 UNIX and C Programming ( Pointers, linked lists, structures, Arrays)
Lab-8 Major File Structure Related System Calls (creat( ),open( ),close( ), read( ) , write( ) , andlseek( ) )
Lab-9,10 Major Process Related System Calls fork,
exec,
wait,
sleep,
exit
The death of a parent or child process
Lab-11 Inter-Process Communication. i.e. Pipes & Signals
Lab-12 Inter Process Communication (IPC)-Using Shared Memory
Lab-13 Threads Creation and Execution Creating Threads
Terminating Thread Execution
Passing Arguments To Threads
Thread Identifiers
Joining Threads
Detaching / Undetaching Threads
8/17/2019 ISC 357 Lab Manual
9/132
9 | P a g e
EVALUATION POLICY
Activity Weight
Lab Work (12 x 0.5%) 6%Lab Quizzes + HWs 9%
Lab Project 6%Total 21%
PROJECT
There will be two mini projects covering the two major topics Shell Programming and Processes/
Threads. Project summary/outline will be provided on the blackboard. Honor the project
submission dead line. After that dead line, a reduction of 20 points for up to 24 hours late
submission and -50 points for up to next 24 hours late submission and after that, submissions
will not be accepted. The projects will be graded only after the student gives a demonstration of
it. Without the demo, the project will not be graded. The projects should be submitted in both
soft copy (through blackboard) and hard copy (printed) in the form of a report with the source
code, along with the detailed explanation of the approach followed.
Notes:
To pass this course, the student must pass the lab-component of the course.
Cheating in whatever form will result in F grade.
Attendance will be checked at the beginning of each Lab.
Absence for three (03) or more unexcused labs will result in a F grade in the Course. An
official excuse must be shown in one week following return to classes.
Every unexcused absence leads to a loss of 0.5 % marks.
Cheating in Lab Work or Lab Project will result F grade in Lab.
Late Submission of Home Works & Projects will not be accepted.
There will be no make-up for any Quiz/Exam/Lab.
Hard work and dedication are necessary ingredients for success in this course.
LABORATORY POLICY
Fallow the laboratory rules listed in appendix “A”
To pass this course, the student must pass the lab-component of the course.
Cheating in whatever form will result in F grade.
Attendance will be checked at the beginning of each Lab.
Absence for three (03) or more unexcused labs will result in a F grade in the Course. Anofficial excuse must be shown in one week following return to classes.
Every unexcused absence leads to a loss of 0.5 % marks.
Cheating in Lab Work or Lab Project will result F grade in Lab.
Late Submission of Home Works & Projects will not be accepted.
There will be no make-up for any Quiz/Exam/Lab.
8/17/2019 ISC 357 Lab Manual
10/132
10 | P a g e
LABORATORY 0: HOW INSTALL UBUNTU 8.10 DESK TOP EDITION
Objective:
Learn How to down load and install UBUNTU 8.10 DESK TOP EDITION in your PC.
Procedure:
The installation of the base system is easy as 1-2-3 because the Ubuntu installer doesn't offer
a lot of options to choose from, so you cannot go wrong.
1. Download the Ubuntu 8.10 desktop edition iso image from
http://www.ubuntu.com/getubuntu/download (or take the CD from your instructor), burn
it onto a CD, and boot your computer from it.
2. Select your language when asked...
3. Select the second option "Install Ubuntu," and hit the “Enter” key...
http://www.ubuntu.com/getubuntu/downloadhttp://www.ubuntu.com/getubuntu/downloadhttp://www.ubuntu.com/getubuntu/download
8/17/2019 ISC 357 Lab Manual
11/132
11 | P a g e
4. Wait for the CD to load into RAM...
5. When the installer appears, you are able to select your native language for the installation
process. Click the “Forward” button to continue...
8/17/2019 ISC 357 Lab Manual
12/132
12 | P a g e
6. Select your location.
The second screen will feature a map of the Earth with little red dots, so you can select your
city/country. Upon the selection of your current location, the time for the final system will
adjust accordingly. You can also select your current location from the drop down list
situated at the bottom of the window.
Click the “Forward” button after you have selected your desired location...
7. Test your keyboard
On the third screen, you will be asked to select the keyboard layout that suits you best(default is U.S. English). You can also test your keyboard on the small text input field
situated at the bottom of the window.
Click the “Forward” button when you have finished wit h the keyboard configuration...
8/17/2019 ISC 357 Lab Manual
13/132
13 | P a g e
8. Hard disk partitioning
Hold on, don't leave just yet! The hard disk partitioning is an easy task, so I am quite sure
you will handle it too. You have three options here:
1. If you want to keep your existing operating system (e.g. Dual boot with Windows XP),select the first option: "Guided - resize the partition and use the freed space." This option will
appear if you have another operating system installed, such as Microsoft Windows. Remember
that, after the installation, the Windows boot loader will be overwritten by the Ubuntu boot
loader!
2. If you want to delete your existing operating system, or the hard drive is already empty
and you want to let the installer automatically partition the hard drive for you, select the
second option, "Guided - use entire disk."
3. Manual is the third choice and it is recommended for advanced users.
WARNING: Be aware that all the data on the selected hard drive or partition will be
ERASED and IRRECOVERABLE.
Click the “Forward” button to continue with the installation...
9. Who are you?
On this screen, you must do exactly what the title says. Fill in the fields with your real name,
the name you want to use to log in on your Ubuntu OS (also known as the “username”), the
password and the name of the computer (automatically generated, but can be overwritten).
Also at this step, there's an option called “Log in automatically.” If you check the box on this
option, you will be automatically logged in to the Ubuntu desktop.
Click the “Forward” button...
8/17/2019 ISC 357 Lab Manual
14/132
14 | P a g e
10. Are you really ready for Ubuntu?
This is the final step of the installation. Here, you can select to install the boot loader on
another partition or hard drive than the default one...
Click the “Install” button to install Ubuntu...
8/17/2019 ISC 357 Lab Manual
15/132
15 | P a g e
The Ubuntu 8.10 (Intrepid Ibex) operating system will be installed...
After approximately 8 to 15 minutes (depending on your computer's specs), a pop-up window
will appear, notifying you that the installation is complete, and you need to restart the computer
in order to use the newly installed Ubuntu operating system.
Click the “Restart Now” button...
http://news.softpedia.com/images/extra/LINUX/large/ubuntu810installation-large_009.jpg
8/17/2019 ISC 357 Lab Manual
16/132
16 | P a g e
11. The CD will be ejected, remove it and press the “Enter” key to reboot...
The computer will be restarted and, in a few seconds, you will see the Ubuntu login screen.
Input your username and password...
8/17/2019 ISC 357 Lab Manual
17/132
8/17/2019 ISC 357 Lab Manual
18/132
18 | P a g e
LABORATORY1: INTRODUCTION TO THE UNIX OPERATING
SYSTEM
Objective:
1. Get familiar with UNIX2. Connect to UNIX machines remotely via Putty
3. Starting UNIX terminal (UBUNTU)
4. Get familiar with UNIX environment
a. Types of UNIX
b. Unix Major Components
c. Files and processes
d. The Directory Structure.
WHAT IS UNIX?
An operating system is the program that controls all the other parts of a computer system - both
the hardware and the software. Most importantly, it allows you to make use of the facilitiesprovided by the system. Example of operating system are Windows XP, Windows NT, UNIX,
Linux, ..etc.
UNIX is an operating system which was first developed in the 1960s, and has been under
constant development ever since. By operating system, we mean the suite of programs which
make the computer work. It is a stable, multi-user, multi-tasking system for servers, desktops
and laptops [1].
UNIX systems also have a graphical user interface (GUI) similar to Microsoft Windows which
provides an easy to use environment. However, knowledge of UNIX is required for operationswhich aren't covered by a graphical program, or for when there is no windows interface
available, for example, in a telnet session [1].
TYPES OF UNIX
There are many different versions of UNIX, although they share common similarities.
The most popular varieties of UNIX are:
Sun Solaris,
GNU/Linux, and
MacOS X.
UNIX MAJOR COMPONENTS
UNIX operating system is made up of three major components the kernel , the Shell , and some
system/ application programs.
1. Kernel
The Kernel is the core of UNIX operating system. It is a large program that is loaded into
memory when the machine is turned on, and it controls the allocation of hardware
8/17/2019 ISC 357 Lab Manual
19/132
19 | P a g e
resources from that point forward. The kernel knows what hardware resources are
available (like the processor(s), memory, the disk drives, network interfaces, etc.), and it has
the necessary programs to talk to all the devices connected to it. It also prevents anyone
from accessing the hardware directly, forcing everyone to use the tools it provides. This way
the kernel provides some protection for users from each other.
2. The Shell
The shell acts as an interface between the user and the kernel. It is a command line
interpreter. It interprets the commands the user types in and arranges for them to be
carried out. It takes each command and passes it to the operating system kernel to be acted
upon. It then displays the results of this operation on your screen. There are several
different shells available for Unix; the most popular are:
/.../sh Bourne shell (sh)
/.../csh C shell (csh)
/.../tcsh TC shell (tcsh)
/.../ksh Korn shell (ksh)
/.../bash Bourne Again SHell (bash)
You can identify which shell you are presently using from the last part of the pathname.
Information about which shell you are using is held in the SHELL environment variable.
Example:
Display the value of the variable SHELL.
Note that the name of environment variable must be given in UPPERCASE
>echo $SHELL/bin/bash
To switch to another shell enter the shell command name at the system prompt.
Example:
This switches you from your current shell to the Bourne shell .
>sh
sh-2.05b>
FILES AND PROCESSES
Everything in UNIX is either a file or a process.
A process is an executing program identified by a unique PID (process identifier).
A file is a collection of data. They are created by users using text editors, running
compilers etc. Types of Unix Files:
1. Ordinary files. This type of file is used to store information, such as some text,
or an image, or Executable or binary file. You can set access permissions to files
which you create – you "own". Any file is always contained within a directory.
8/17/2019 ISC 357 Lab Manual
20/132
20 | P a g e
2. Directories. A directory is a file that holds other files and other directories. You
can set access permissions to directory which you create. i.e. you own them.
3. Special files. This type of file is used to represent a real physical device such as a
printer, tape drive or terminal.
4. Pipes. UNIX allows you to link commands together using a pipe. The pipe acts asa temporary file, which only exists to hold data from one command until it is
read by another.
THE DIRECTORY STRUCTURE
All the files are grouped together in the directory structure. The file-system is arranged in a
hierarchical structure, like an inverted tree. The top of the hierarchy is traditionally called root
(written as a slash / ).
The /bin directory contains the commands and utilities that you use day to day. These
are executable binary files - hence the directory name bin.
The /dev directory contains special files used to represent real physical devices such as
printers and terminals.
The /etc directory contains various commands and files which are used for system
administration
The /home directory contains a home directory for each user of the system.
The /lib directory contains libraries that are used by various programs and languages.
The /tmp directory acts as a "scratch" area in which any user can store files on a
temporary basis.
The /usr directory contains system files and directories that you share with other users.
Application programs, on-line manual pages, and language dictionaries typically reside
here.
8/17/2019 ISC 357 Lab Manual
21/132
21 | P a g e
ACCESSING UNIX SYSTEM
There are many ways that you can access a UNIX system:
The main mode of access to a UNIX machine is through a terminal, which
usually includes a keyboard, and a video monitor. For each terminal connectedto the UNIX system, the kernel runs a process called a tty that accepts input from
the terminal, and sends output to the terminal.
Personal computers can be used to emulate terminals, so that they can be
connected to a UNIX machine. PCs are connected to UNIX machines directly or
remotely.
CONNECTED TO UNIX MACHINES REMOTELY VIA PUTTY
1. You will find Putty program installed in the pc’s in the laboratory.
2. Launch Putty: Double-click on the PUTTY program to get Configuration window.
3. Enter the server IP- 139.141.169.188 in the field for 'Host Name (or IP address) and
select 'SSH' radio button for connection type.
4. Then simply press the 'Open' button.
8/17/2019 ISC 357 Lab Manual
22/132
22 | P a g e
The regular PUTTY terminal window will pop up, as it is shown in the figure below. Enter your
username and password. Note that while you are typing your password cursor will not be
moved.
STARTING UNIX TERMINAL
To open an UNIX terminal window, click on the "Terminal" icon from Applications/Accessoriesmenus.
An UNIX Terminal window will then appear with a % prompt, waiting for you to start entering
commands.
8/17/2019 ISC 357 Lab Manual
23/132
23 | P a g e
8/17/2019 ISC 357 Lab Manual
24/132
24 | P a g e
LABORATORY2,4: UNIX COMMANDS
Objective
1. Understand Unix Directory Management Commands2. Know File Manipulation Commands
3. Find out How to Enter more than one command
4. Find out How to Redirecting standard input and output5. Learn Access Permissions commands6. Study Miscellaneous Command7. Learn Process related commands
COMMAND SYNTAX RULES
A command is a program that tells the UNIX system to do something.
A command, or a program, interacts with the kernel to perform the functions called by the
user. A program can be:
an executable shell file, known as a shell script,
built-in shell command, or
a source compiled, object code file.
command [options][arguments]
Commands are case sensitive.
An option: modifies the command, changing the way it performs. Options are generallypreceded by a hyphen (-) and for most commands, more than one option can be used
together.
argument: indicates on what the command is to perform its action, usually a file or
series of files.
Any options or arguments enclosed in [ ] square brackets are optional.
Anything not enclosed in [ ] square brackets must be entered.
Boldface words are considered to be literals and must be typed exactly as they appear.
This usually applies to the command name and command options.
Arguments shown in italics must be replaced by whatever it is that they represent. This
is usually the name of a file or directory.
Ellipses '...' mean that the previous argument can be repeated any number of times.
8/17/2019 ISC 357 Lab Manual
25/132
25 | P a g e
UNIX DIRECTORY MANAGEMENT COMMANDS
PRINTING WORKING DIRECTORY COMMAND - pwd
pwd
Display the pathname of the current working directory
Example:
>pwd
/home/ISC357/091/maryam2
Which means that maryam2 (your home directory) is in the sub-directory 091 (the group
directory), which in turn is located in the ISC357 sub-directory, which is in the home sub-
directory, which is in the top-level root directory called " / "(see the figure below) .
CHANGING DIRECTORY- cd
cd [directory]
Changing working directory
Examples:
This moves you up to the root
> cd /
This moves you down to your HOME directory.
cd ~
>cd /usr>pwd
/
home
ISC35
091 082
maryam2…… Abrar
bin tmp usr dev …
test.c report.docMyfolder
8/17/2019 ISC 357 Lab Manual
26/132
26 | P a g e
/usr
This moves you down one level from current directory to subdirectory bin
>cd bin
>pwd
/usr/bin
>cd usr/etc
>pwd
usr/etc
Move up the directory tree without entering the pathname
>cd ..
>pwd
/usr
This moves you down one level from current directory to subdirectory start with letter e ,
for example usr/etc .
>cd e*
This moves you up one level in the directory tree and then moves you into usr/bin the
subdirectory bin
>cd ../bin
(.) means the current directory, in other word stay where you are. Note: there is a space
between cd and the dot. This may not seem very useful at first, but using (.) as the name of
the current directory will save a lot of typing, as we shall see later in the tutorial.
>cd .
8/17/2019 ISC 357 Lab Manual
27/132
27 | P a g e
LIST -ls
ls [-aAcCdfFgilLqrRstu1] [filename]
List the contents of a directory
options Description
-a List all entries; even the hidden file that begin with ‘.’(dot)
-A Same as –a, except that ‘.’ and ‘..’ are not listed
-c Use time of last edit (or last mode change) for sorting or printing
-C Force multiple-column output, with entries sorted down the columns .This is the default when
output is to terminal.
-d If argument is a directory, lidt only its name(not its contents);often used with –l to get the
status of a diectory.
-F Mark directories with a trailing slash (‘/’), executable files with a trailing asterisk(‘*’), symbolic
links with a trailing at-sign (‘@’), and AF_UNIX address family sockets with a trailing equals
sign(‘=‘)
-l list in long format, access permissions, number of links, owner, size in bytes, and time of last
modification for each file. If the file is a special file the size field will instead contain the major
and minor device numbers. If the time of last modification is greater than six months ago, it is
shown in the format ‘month date year’; files modified within six months show ‘month date
time’ .If the file is a symbolic link the path name of the linked-to file is printed preceded by ‘->’.
-L If argument is a symbolic link, list the file or directory the link references rather than the link
itself.
-q Display non-graphic characters in filenames as the character ?; for ls, this is the default when
output is to a terminal.
-r Reverse the order of sort to get reverse alphabetic or oldest first as a appropriate.
-R Recursively list subdirectories encountered.
-s Give size of each file, including any indirect blocks used to map the file, in kilobytes.
-t Sort by time modified (latest first) instead of by name.
-u Use time of last access instead of last modification for sorting (with t option) and/or printing
(with the –l option)
-1 Force one entry per line output format; this is the default when output is not to terminal
8/17/2019 ISC 357 Lab Manual
28/132
28 | P a g e
Examples:
>ls
bin dev home lib misc usr boot etc tmp var Examples:
>ls -F
/bin /dev /home /lib /misc /usr /boot /etc /tmp /var
>ls –a
. .. .autofsck bin dev home lib misc usr boot etc
>ls –Fa
. .. .autofsck /bin /dev /home /lib /misc /usr /boot /etc
>ls m*
myfile maryam.tar
>ls –l
rwxr-xr-x 1 ahmed staff 3649 Feb 22 15:51 prog.c
In the example above, this first item -rwxr-xr-x represents the access permissions on
this file.
The owner has read,write and execute permissions.
The group has read and execute permissions.
All other user has execute permissions.
The next items represent the number of links (1) to it; the username (ahmed ) of the
person owning it; the name of the group (staff ) which owns it; its size in bytes (3649);
MAKE A DIRECTORY-mkdir
mkdir directory Name
Make a directory or directories
Examples:
This creates the directory maryam in the current directory
>mkdir maryam
This creates the directory presentations in the parent
directory of the current working directory
>mkdir . . / presentations
>mkdir ~/test/test1
8/17/2019 ISC 357 Lab Manual
29/132
29 | P a g e
REMOVE DIRECTORY
rmdir directory
Remove an empty directories
Example :
The directory must be empty before you can delete it
>rmdir maryam
rm -r directory
Deletes all the contents of the directory including any subdirectories.
Examples:
Current working
directory command Result
home/isc357> mkdir lab1
home/isc357> mkdir ../ lab2
home/isc357> mkdir home/ lab3
8/17/2019 ISC 357 Lab Manual
30/132
30 | P a g e
COPY -cp
cp [ -ip ] filename1 filename2
Copy the content of filename1 into filename2.
cp –rR [ ip ] directory1 directory2
Recursively copies directory1, along with its contents and subdirectories to
directory2
Directory2 is created if it does not exist, and directory1 is created as a
subdirectory within it.
cp [-iprR] filename … directory
Copy the filename/s in the indicated directory
Options Description
-i Interactive, Prompt for confirmation whenever the copy would overwrite an existing file. Ay answer confirms that the copy should proceed. Any other answer confirms cp fromoverwriting the file.
-p Preserve. Duplicate not only the contents of the original file or directory, but also themodification time and permission modes.
-r/R Recursive. If any of the source files are directory, copy the directory along with itsfiles(including any subdirectories and their files); the destination must be directory.
... The dot is shorthand for the parent directory.
. The dot is shorthand for the current directory.
Examples:
>ls ~/maryam/programs
Prog1 prog1.p
> cp ~/maryam/programs/prog1.p ~/maryam/programs/prog1.old
>ls ~/maryam/programs
Prog1 prog1.old prog1.p>cp –r ~/maryam/programs ~/maryam/oldprograms
>ls ~/maryam/oldprograms
Prog1 prog1.old prog1.p
>mkdir ~/tmp
>cp ~/oldprograms/*.* ~/tmp
>Ls ~/tmp
prog1 prog1.old prog1.p
ls –R ~/maryam
8/17/2019 ISC 357 Lab Manual
31/132
31 | P a g e
MOVE-mv
mv[ -fi ] filename1 filename2
Rename filename1 as filename2
mv –[ fi ] directory1 directory 2
mv[-fi] filename … directory
Options Description
-f Force. Override any mode restrictions and the –I option. The –f option
also suppresses any warning messages about modes which would
potentially restrict overwriting.
-I Interactive mode. mv displays the name of the file or directory followed
by a question mark whenever a move would replace an existing file or
directory. If you type a line starting with y, mv moves the specified file ordirectory, otherwise mv does nothing with that file or directory.
DISPLAY FILE CONTENT- cat, more, less, head, tail
cat[ -bens] filename
Display the contents of a file on the screen
Example:
>cat –n testfile1 Hello
2 i this is my first file text file
3
4
5 bye
>cat testfile -sn
1 Hello
2 i this is my first file text file
3
options Description
-b number nonblank output lines
-e Display nonprinting character and display $ at end of each line
-n number all output lines, even blank lines.
-s Squeeze blank never more than one single blank line
8/17/2019 ISC 357 Lab Manual
32/132
32 | P a g e
4 bye
more filename
Display the contents of a file on the screen.
less filename
Display the contents of a file on the screen. Press the [space-bar] if you
want to see another page, and type [q] if you want to quit reading. As you
can see, less is used in preference to cat for long files.
head -n filename
Display the first n number of lines of a text file use the command.
Displays only first 10 lines if the option of n is not specified
tail -n filename
display the last n number of lines of a text file use the command. Displays
only last and last 10 lines respectively if the option of n is not specified
Example:
Display the first three lines
>head -3 testfile
Displays last and last 10 lines
>tail testfile
FINDING A FILE – find
find pathname -name filename
Keyboard Description
space bar Display next page of text.
Display next line of text.
q Quit from reading.
d Scroll forwards about half a screen of text.
b Skip backwards one screen of text.
h Display a list of commands (help).
8/17/2019 ISC 357 Lab Manual
33/132
33 | P a g e
This command locates a file in the file system.
Pathname: where to search i.e. defines the directory to start from.
You can define the filename using wildcards. If these are used, the
filename must be placed in 'quotes'.
To search in the whole system for any files named foo and display their pathnames.
>find / -name foo
To find program.c file starting from the current directory: If the file is not found nothing
is displayed.
>find . –name program.c -print
Find all files with the extension .c under the current directory.
>find . -name '*.c' -print
To search in /home/isc357/091/maryam2 for all files with name contains tt letters.
find /home/isc357/091/maryam2 -name '*tt*‘
SEARCHING THE CONTENTS OF A FILE
grep [options] regexp [ file(s)]
- used to search for generalized regular expression inside Unix file.
- regexp is a regular expression. It is preferred to be specified single
quotes.
- Options: can be one of the options described in the table below:
Commonoptions
Meaning
-i ignore case
-c report only a count of the number of lines containing matches, not thematches themselves
-v invert the search, displaying only lines that do not match
-n display the line number along with the line on which a match was found
-s work silently, reporting only the final status:0, for matche(s) found1, for no matches2, for error
-l list filenames, but not lines, in which matches were found.
Searches for the string copying in the file help and displays the lines related.
>grep copying help
Find and display each line in the file tasks that contains the pattern don't or Don't. The line
number for each line is also displayed.
>grep -n '[dD]on\'t' tasks
List only those students currently login to your server.
>who | grep ‘st*’
Count number of directories in your current work directory.
8/17/2019 ISC 357 Lab Manual
34/132
34 | P a g e
>ls –F | grep –c ‘/$’
DETERMINE FILE TYPE
file filename
This command determines the type of a file, or to find out if executable
files contain shell scripts, or are binaries. Shell scripts are text files and
can be displayed and edited.
Example:
file *
file testdir
ENTERING MORE THAN ONE COMMAND
To enter several commands on one command line, use a ; (semicolon) to separate each one
from the next.
Example:
This command line contains two commands. The first, cd .. changes the current directory to
the parent directory. The second, ls -l produces a long listing of the contents of the current
directory. If necessary you can continue the commands onto another line.
> cd .. ; ls –l
REDIRECTING STANDARD INPUT AND OUTPUT
UNIX considers any device attached to the system to be a file. By default, a command treats your
terminal as the standard input file from which to read in information. Your terminal is also
treated as the standard output file to which information is sent from the command. This action
can be changed by redirecting standard input and standard output from and to any other file.
Symbol Description
command file To redirect the standard output from a command. If the file that youredirect standard output to does not already exists it will be created.
command >>file To append the standard output from a command to a file
command1 | command2 pipe the output of command1 to the input of command2
Example:This redirects the standard output from the man command so that it goes to the file
hlp1.txt
man mkdir > hlp1.txt.
8/17/2019 ISC 357 Lab Manual
35/132
35 | P a g e
This creates a file called list1,then you can start type the content you desire till you type
^D it will save the content and exit.
cat > list1
Then start to type in file, ex: .
pearbananaapple
you can use [Return] ,^ D {this means press [Ctrl] and [d] to stop}
This creates a file called chapt2 with the same contents as part1.
cat part1 > chapt2
It then reads the contents of part2 and appends them to the file chapt2. The file chapt2
now contains the data from part1 followed by the data from part2.
cat part2 >> chapt2
Concatenate file1 and file2 to file0
cat file1 file2 > file0
ACCESS PERMISSIONS
UNDERSTANDING ACCESS PERMISSIONS
There are three types of permissions:
r read the file or directory w write to the file or directory x execute the file or search the directory
Each of these permissions can be set for any one of three types of user:
u the user who owns the file (usually you) g members of the group to which the owner belongs all other users
The access permissions for all three types of user can be given as a string of nine characters: user group others
r w x r w x r w x
DISPLAYING ACCESS PERMISSIONS
To display the access permissions of a file or directory use the ls command:
ls –l filename or directory
Example:
The owner of the file has read and write permissions and no permissions to others.
>ls –l file1
-rw------- 2 ahmed 3287 Apr 8 12:10 file1
8/17/2019 ISC 357 Lab Manual
36/132
36 | P a g e
The owner has read and write permissions. Everyone else - the group and all other users
- can read the file.
>ls -l testfile
-rw-r--r-- 2 ahmed 3287 Apr 8 12:11 file2 ……
DEFAULT ACCESS PERMISSIONS
The default access permissions for new created file: rw------- gives you read and write
permission for your files “owner”; no access permissions for the group or others.
The default access permission s for newly created directory: rwx------ gives you read , write
and execute permission for your directories “owner”; no access permissions for the group
or others. Access permissions for your home directory are usually set to rwx--x--x or rwxr-
xr-x.
CHANGING ACCESS PERMISSIONS
chmod [-fR] mode filename
chmod [-fR] mode directory_name
Only the owner of a file (or the super user) may change its mode.
-f: Force. -R: Recursive
The mode can be changed using absolute “Numeric” or symbolic value.
1. An absolute mode: is setting permissions by using octal numbers (Read 4 , write 2 and
execute 1). see the table below. 2. Symbolic mode has the form: [who] op permission [ permission]
who : u, g, o, a. If who is omitted, the default is a. op permission: +, -, =. Permission: r, w, x.
Examples:
op Description
+ To add the permissions
- To remove permissions
= To assign the permission explicitly
Setting Access Permissions Numerically
Description
1 execute only
2 write only
3 write and execute (1+2)
4 read only
5 read and execute (4+1)
6 read and write (4+2)
7 read and write and execute (4+2+1)
Symbolic mode
who Description
u User’s permissions
g Group permissions
o Others
a ALL
8/17/2019 ISC 357 Lab Manual
37/132
37 | P a g e
Give members of your group permission to read a file.
>chmod g+r file2
It denies write permission to others for file1.
>chmod o-w file1
To gives read and write and execute for owner, and read and execute for group andothers
>chmod 755 newfile
PROCESS RELATED COMMANDS
WHAT IS A PROCESS?
A process is a name given to a program being executed by the operating system.
It may be a “system'' program (e.g login, update, csh) or program initiated by the user
(pico, a.out or a user written one).
When you login to the system a process is started to run your shell program “init” ”, and
its PID is 1. Any processes that are started from within your shell - such as entering a
command - are the children of this process. A process can have many children, but only
one parent.
You can have multiple processes executing the same program, but each process has its
own copy of the program within its own address space and executes it independently of
the other copies.
Each process created on the system has a unique number (a process ID), known as its
PID, associated with it.
UNIX command ps will list all current processes running on your machine and will
list the pid.
MONITORING PROCESSES
ps [-option]
Without options to list all the processes owned by you and associatedwith your terminal.
The information displayed by the ps command varies according to which command option(s)
you use and the type of UNIX that you are using.
These are some of the column headings displayed by the different versions of this command.
PID SZ (size in Kb) TTY (controlling terminal) TIME (used by CPU) COMMAND
Example:
Display information about all your processes.> ps -u
8/17/2019 ISC 357 Lab Manual
38/132
38 | P a g e
Display information about your processes those are currently running.
> ps
>ps -ef
UID PID PPID C STIME TTY TIME CMDroot 0 0 0 2 0:15:23 ? 0:14 sched
root 1 0 0 20:15:24 ? 0:00 /sbin/init
root 2 0 0 20:15:24 ? 0:00 pageout
root 3 0 0 20:15:24 ? 0:00 fsflush
daemon 240 1 0 20:16:37 ? 0:00 /usr/lib/nfs/statd ...
The first three columns are important. The first lists the user the process is running as, the
second lists the ID of the process, and the third lists the ID of the parent of the process. The final
column is a description of the process, usually the name of the binary that was launched.
The presence of a parent PID (PPID) implies that one process is created by another process.
The original process that kicks this off is called init, and it is always given a PID of 1. init is the
first real process to be started by the kernel on bootup. It is the job of init to start up the rest of
the system. init and other processes with a PPID of 0 belong to the kernel.
sleep time
Waits a amount of seconds. time The amount of seconds to wait..
wait [ pid ] [ jobid ]Await process completion.
pid process ID of a command, for which the utility is to wait for the
termination.
Jobid job ID that identifies a background process group to be waited for.
Example:
Sleeps for 10 seconds
>sleep 10
Wait on pid 2017 until termination
> wait 2017
MANAGING JOBS AND PROCESSES
Canceling a foreground process To cancel the process that is currently running enter
the key combination: Ctrl-c. This cancels the current foreground process completely: it
no longer exists.
Suspending a foreground process To suspend a foreground process enter the key
combination: Ctrl-z. This stops the current foreground process. If you are using the
Bourne shell you will then have to kill the process. Other shells provide you with a
facility to restart a process in the foreground or as a background job.
8/17/2019 ISC 357 Lab Manual
39/132
8/17/2019 ISC 357 Lab Manual
40/132
40 | P a g e
MISCELLANEOUS COMMAND
man command
It show a brief manual in a clear text format for most of the commands
available on your Unix OS and provides cross-references to other similar
manuals. Press the [space-bar] if you want to see another page, and type
[q] if you want to quit reading
All the manuals for UNIX commands are split into clearly marked sections:
NAME - command name as it should be typed
SYNOPSIS - syntax for running a command – all the possible command line options
DESCRIPTION - textual description of what a command is used for
OPTIONS - full list of command line options with thorough explanations
FILES - files which are used by a command
SEE ALSO – other relevant commands you might want to look at
BUGS - known bugs and limitations of a command
AUTHOR - list of command authors, developers and most current maintainers
Example:
Press the [space-bar] if you want to see another page, and type [q] if you want to quit
reading
>man cd
history
It displays a numbered list of commands in the order in which you have
used them.
command Description
!! Run the previous command
!n Run command number n
!string Run most recent command starting with characters in string
!?string Run most recent command containing characters that match string
Repeat the last command
>!!
Display all history of command
>history
1 ls
2 man ls
3 mkdir t6
4 pwd
……
8/17/2019 ISC 357 Lab Manual
41/132
41 | P a g e
Run the last command start with mkdir
>!mkdir
command Description
who Displays who is currently logged in the system
finger [userid] It dispays information about a specified userid
echo It prints message to stdout (your standard output file)
tty It shows special file that represents your terminal.
Id It displays the userid and groupid
Clear Clears the terminal screen
Hostname Displays the name of your Unix system
calcal cal
Displays the calendar of current month and yearDisplays the calendar of the specified year Displays the calendar of the specified month’s number and year
wc –c wc –w wc –l
Counts number of characters in the specified file name Counts number of words in the specified file name Counts number of lines in the specified file name
EXCERSICES
1. Write a command to store a list of your files names in the home directory and the
subdirectories in a text file called myfilesList.txt . (Hint: use redirect standard
output ).
2. Create a file named as lab2.txt by using vi editor . Write at least 5 sentences in this file.
3. Write a command to count number of characters, words and lines in lab2.txt , you have
created in problem#2.
4. Write a command to count number of words in the first line of lab2.txt , you have created
in problem#2. (Hint: use pipe
).
5. Write a command to count number of words in the last line of lab2.txt. , you have created
in problem#2. (Hint: use pipe ).
8/17/2019 ISC 357 Lab Manual
42/132
42 | P a g e
LABORATORY 5, 6: SHELL PROGRAMMING
Objective
1. User defined variables 1. Reading Values into User-defined Variables (Reading user input)
2. Command Substitution
3. Computation on Shell Variables
2. Pre-defined shell variables
1. Passing arguments to the shell
3. Conditional Execution Operators
4. Conditional statements
1. The if statement
2. The case statement
5. Flow of control statements
1. The for statement 2. The while and until statements
3. The break and continue statements
OVERVIEW OF SHELL
Shell
The shell acts as an interface between the user and the kernel. It is a command line interpreter.
It interprets the commands the user types in and arranges for them to be carried out. It takes
each command and passes it to the operating system kernel to be acted upon. It then displaysthe results of this operation on your screen. There are several different shells available for Unix;
Three most widely used shells in UNIX are Bourne shell, C shell, and Korn shell.
Shell Scripts and Uses
A shell script or a shell program is a series of commands put in a file and executed by the
Shell. Bourne Again shell will be used to create shell scripts.
Since the user cannot interact with the kernel directly, Shell Programming skills are a must to be
able to exploit the power of UNIX to the fullest extent. A shell script can be used for variety of
tasks, such as:
Customizing the user work environment. For Example user can write a shell script to see
the current date, a welcome message, and the list of users who have logged on, every
time user login.
Automating your daily tasks. For example, to back up all the programs at the end of the
day.
Automating repetitive tasks.
Executing important system procedures, like shutting down the system, formatting a
disk, creating a file system etc.
Performing some operations on many files.
8/17/2019 ISC 357 Lab Manual
43/132
43 | P a g e
Shell Variables
The variables in the Bourne Shell are classified as:
User defined variables: defined by the user for his use (e.g age=32).
Environmental variables: defined by shell for its own operations (PATH, HOME, TERM,
LOGNAME, PS1, SHELL e.t.c). Predefined variables: reserved variables used by the shell and UNIX commands for
specifying the exit status of command, arguments to the shell scripts, the formal parameters
e.t.c.
USER DEFINED VARIABLES
Examples:
#variable name is assigned a value Ali
>name=Ali#Ali will be displayed
>echo $name
Ali
#See output of this in your computer
>echo Hello $name ! , Welcome to $HOME
READING VALUES INTO USER-DEFINED VARIABLES (READING USER INPUT):
readIn shell script read command, used to read standard input.
Example:
It prompts the user for input, assigns this to the variable name and then displays the value
of this variable to standard output.
>cat lab5_0
>echo "Please enter your name:"
>read name
>echo "Welcome to CFW, ISC $name"
Running the file lab4_0?
>chmod u+x lab5_0
> ./lab5_0
Please enter your name:
Dr. Kalim Qureshi
Welcome to CFW, ISC Dr. Kalim Qureshi.
http://www.mcsr.olemiss.edu/unixhelp/glossary/gs.html#stdinhttp://www.mcsr.olemiss.edu/unixhelp/glossary/gs.html#stdouthttp://www.mcsr.olemiss.edu/unixhelp/glossary/gs.html#stdouthttp://www.mcsr.olemiss.edu/unixhelp/glossary/gs.html#stdin
8/17/2019 ISC 357 Lab Manual
44/132
44 | P a g e
If there is more than one word in the input, each word can be assigned to a different variable.
Any words left over are assigned to the last named variable.
Example:
echo "Please enter your surname\n"
echo "followed by your first name: \c"
read name1 name2
echo "Welcome to ICS Dept, KFUPM , $name2 $name1"
Example:
This shell script will accept the name and age from the user and display the same on the
terminal screen.
>cat lab5_1
echo “Enter your name : \c”
read name
echo “Enter your age : \c”
read age
echo “Hello $name , nice to meet you. You are $age years old”
Example:
This script takes two file names and copies the first file into the second one
>cat lab5_2
echo “Please Enter source file name :\c” read source
echo “Enter the target file name :\c”
read target
cp $source $target
echo file $source is copied into the $target
COMMAND SUBSTITUTION:
Format for command substitution is:
var = `command` (where ‘ ‘ is back quote)
Example:
It will display the output of date command
>echo ‘date’
Check the output of this script
>echo there are ‘who | wc –l’ users working on the system
8/17/2019 ISC 357 Lab Manual
45/132
45 | P a g e
COMPUTATION ON SHELL VARIABLES
Various forms for performing computations on shell variables using expr command are:
expr val_1 op val_2 # (Where op is operator)
expr $val_1 op $val_2
val_3 = `expr $val_1 op $val_2`
Examples:
Gives 12
>expr 5 + 7
Gives 3
>expr 6 – 3
Gives 12
>expr 3 \* 4
Gives 8
>expr 24 / 3
>sum=’expr 5 + 6’
Gives 11
>echo $sum
>a=12
>b=90
Will display sum is 12 + 90
>echo sum is $a + $b
Gives sum is 102
>echo sum is `expr $a + $b`
PRE-DEFINED SHELL VARIABLES
There are some variables which are set internally by the shell and which are available to the
user. These variables are called Pre-defined shell variables. The table below list such variables:
Name Description$1 - $9 These variables are the positional parameters
$0 The name of the command currently being executed$# The number of positional arguments given to this invocation of the shell, Parameter
Count.$? The exit status of the last command executed is given as a decimal string. When a
command completes successfully, it returns the exit status of 0 (zero), otherwise itreturns a non-zero exit status.
$$ The process number of this shell - useful for including in filenames, to make themunique (PID of Current Shell).
$! The process id of the last command run in the background (It holds PID of last
background process).$- The current options supplied to this invocation of the shell.
http://www.mcsr.olemiss.edu/unixhelp/scrpt/scrpt2.1.htmlhttp://www.mcsr.olemiss.edu/unixhelp/scrpt/scrpt2.1.html
8/17/2019 ISC 357 Lab Manual
46/132
46 | P a g e
$* A string containing all the arguments to the shell, starting at $1, i.e. All Parameters.
$@@ Same as above, except when quoted.
Notes:
$* and $@@ when unquoted are identical and expand into the arguments.
"$*" is a single word, comprising all the arguments to the shell, joined together with spaces. For
example '1 2' 3 becomes "1 2 3".
"$@@" is identical to the arguments received by the shell, the resulting list of words completely
match what was given to the shell. For example '1 2' 3 becomes "1 2" "3"
PASSING ARGUMENTS TO THE SHELL
Shell scripts can act like standard UNIX commands and take arguments from the command line.
Arguments are passed from the command line into a shell program using the positionalparameters $1 through to $9. Each parameter corresponds to the position of the argument on
the command line.
The positional parameter $0 refers to the command name or name of the executable file
containing the shell script. Only nine command line arguments can be accessed, but you can
access more than nine using the shift command. All the positional parameters can be referred
to using the special parameter $*. This is useful when passing filenames as arguments.
Example
This is shell script, which will accept 5 numbers as parameters and display their sum. Also
display the contents of the different variables in the script. >cat lab5_3
echo the parameters passed are : $1, $2, $3, $4, $5
echo the name of the script is : $0
echo the number of parameters passed are : $#
sum=`expr $1 + $2 + $3 + $4 + $5`
echo The sum is : $sum
SHIFT COMMAND
If more than 9 parameters are passed to a script, it is not possible to refer to the parameters
beyond the 9th one. This is because shell accepts a single digit following the dollar sign as a
positional parameter definition.
The shift command is used to shift the parameters one position to the left. On the execution of
shift command the first parameter is overwritten by the second, the second by third and so on.
This implies that the contents of the first parameter are lost once the shift command is executed.
8/17/2019 ISC 357 Lab Manual
47/132
47 | P a g e
Example
Write a script, which will accept different numbers and finds their sum. The number of
parameters can vary.
>cat lab5_4
sum=0
while [ $# -gt 0 ]
do
sum=’expr $sum + $1’
shift
done
echo sum is $sum
Here, the parameter $1 is added to the variable sum always. After shift, the value of $1 will be
lost and the value of $2 becomes the value of $1 and so on.
The above script can also be written without using the shift command as:
for i in $*
do
sum=’expr $sum + $i’
done
Usually only nine command line arguments can be accessed using positional parameters. The
shift command gives access to command line arguments greater than nine by shifting each of thearguments. The second argument ($2) becomes the first ($1), the third ($3) becomes the
second ($2) and so on. This gives you access to the tenth command line argument by making it
the ninth. The first argument is no longer available.
Successive shift commands make additional arguments available. Note that there is no "unshift"
command to bring back arguments that are no longer available!.
Example
To successively shift the argument that is represented by each positional parameter:
> cat shift_demoecho "arg1=$1 arg2=$2 arg3=$3"
shift
echo "arg1=$1 arg2=$2 arg3=$3"
shift
echo "arg1=$1 arg2=$2 arg3=$3"
shift
echo "arg1=$1 arg2=$2 arg3=$3"
8/17/2019 ISC 357 Lab Manual
48/132
48 | P a g e
Runing example above
>./shift_demo one two three four five six seven
arg1=one arg2=two arg3=three
arg1=two arg2=three arg3=four
arg1=three arg2=four arg3=five
arg1=four arg2=five arg3=six
arg1=five arg2=six arg3=seven
CONDITIONAL EXECUTION OPERATORS
Conditional execution of commands are useful when we want to execute the command based on
the status of the previous command, i .e whether the previous command has succeeded or
failed. This is examined by the exit status of each command. For success of any command exitstatus will be 0 (zero) and 1 (One) if unsuccessful.
&& ( e.g command1 && command2)
The operator && executes the command(s) following it (e.g command2),
if and only if the preceding command (e.g command1) was successfully
compiled.
|| (Double pipe)
The || operator executes the command(s) following it e.g command2), if
the preceding command failed (e.g command1).
Examples
The above command will remove mydoc.doc if it exits, otherwise, it will do nothing.
%ls | grep “mydoc.doc” && rm mydoc.doc
The above command will display the contents of mydoc.doc if it exists otherwise file not
found displayed.
%cat mydoc.doc || echo “file not found”
In case, more than one command is to be executed or more than one condition need to be
checked simultaneously, then this type of conditional execution is not helpful. In such cases the
if-then-elif-else-fi statement is used.
8/17/2019 ISC 357 Lab Manual
49/132
49 | P a g e
CONDITIONAL STATEMENTS
THE IF STATEMENT
The if statement uses the exit status of the given command and conditionally executes the
statements following.
The general syntax is:
if test
then
commands (if condition is true)
else
commands (if condition is false)
fi
then, else and fi are shell reserved words and as such are only recognized after a new line or ;
(semicolon). Make sure that you end each if construct with a fi statement.
NESTED IF STATEMENT
if (-----)
then ...
else if ...
...
fi
fi
The elif statement can be used as shorthand for an else if statement.
Example:
if (------)
then ...
elif ...
...
fi
TEST COMMAND
The Unix system provides test command, which investigates the exit status of the previous
command, and translates the result in the form of success or failure, i.e either a 0 or 1.
8/17/2019 ISC 357 Lab Manual
50/132
50 | P a g e
The test command does not produce any output, but its exit status can be passed to the if
statement to check whether the test failed or succeeded.
All commands return the exit status to a pre-defined Shell Variable ‘?’. Which can be displayedusing the echo command. Every Unix command returns a value on exit, which the shell can
interrogate. This value is held in the read-only shell variable $?. A value of 0 (zero) signifiessuccess; anything other than 0 (zero) signifies failure.
echo $?
If output of this is 0 (Zero) it means the previous command was successful and if output is 1
(One) it means previous command failed.
The test command has specific operators to operate on files, numeric values and strings,which are explained below:
1. Operators on Numeric Variables used with test command:
-eq : equal to
-ne : not equals to
-gt : grater than
-lt : less than
-ge : greater than or equal to
-le : less than equal to
Example:
> a=12; b=23
> test $a –eq $b
Gives 1 (one) as output.(Indicates exit status false)
>echo $?
2. Operators on String Variables used with test command:
= : equality of strings
!= : not equal
-z : zero length string (i.e string containing zero character i.e null
string).
-n : String length is non zero.
8/17/2019 ISC 357 Lab Manual
51/132
51 | P a g e
Examples:
$> name=”Ahmad”
Will return the exit status 1 as the string name is not null.
>test –z $name
Will return 0 as the string is not null.
>test –n $name
Will return 0 as the variable has not been defined.
>test –z “$address”
Will return 1 as the value of name is not equal to “Ali”
>test $name = “Ali”
3. Operators on files used with test command:
-f : the file exists.
-s : the file exists and the file size is non zero.
-d : directory exists.
-r : file exits and has read permission.
-w : file exists and has write permission.
-x : file exists and has execute permission.
Examples:
Will check for the file mydoc.doc , if exists, returns 0 else 1.
>test –f “mydoc.doc”
Will check for read permission for mydoc.doc
>test –r “mydoc.doc”
Will check for the existence of the users home directory.
>test –d “$HOME”
4. Logical Operators used with test command:
Combining more than one condition is done through the logical AND, OR
and NOT operators.
-a : logical AND
-o : logical OR
! : logical NOT
8/17/2019 ISC 357 Lab Manual
52/132
52 | P a g e
Example:
Will check both the read and write permission for the file mydoc.doc and returns either 0
or 1, Depending on result.
> test –r “mydoc.doc” –a –w “mydoc.doc”
Example
To carry out a conditional action:
if who | grep -s rafiq > /dev/null
then
echo rafiq logged in 357 Lab
else
echo rafiq available in 357 Lab
fi
This lists who is currently logged on to the system and pipes the output through grep to search
for the username rafiq. The -s option causes grep to work silently and any error messages are
directed to the file /dev/null instead of the standard output.
If the command is successful i.e. the username rafiq found in the list of users currently logged in
then the message rafiq logged in 357 Lab is displayed, otherwise the second message is
displayed.
THE CASE STATEMENT
The case statement case is a flow control construct that provides for multi-way branching basedon patterns.
Program flow is controlled on the basis of the WORD given. This WORD is compared with each
PATTERN in order until a match is found, at which point the associated COMMAND(S) are
executed. When all the commands are executed control is passed to the first statement after the
esac. Each list of commands must end with a double semi-colon (;;).
case WORD in
PATTERN1) COMMAND(S ) ;;
PATTERN2)
COMMAND(S ) ;;
-----------------------
-----------------------
PATTERNN) COMMAND(S) ;;
*) default command ;;
esac
http://www.mcsr.olemiss.edu/unixhelp/utilities2/grep.htmlhttp://www.mcsr.olemiss.edu/unixhelp/utilities2/grep.htmlhttp://www.mcsr.olemiss.edu/unixhelp/utilities2/grep.htmlhttp://www.mcsr.olemiss.edu/unixhelp/utilities2/grep.html
8/17/2019 ISC 357 Lab Manual
53/132
53 | P a g e
A command can be associated with more than one pattern. Patterns can be separated from each
other by a | symbol. For example:
case WORD in
PATTERN1|PATTERN2) COMMAND
... ;;
Patterns are checked for a match in the order in which they appear. A command is alwayscarried out after the first instance of a pattern. The * character can be used to specify a default
pattern as the * character is the shell wildcard character.
Examples:
> cat Lab4_5
# Display a menu of options and depending upon the user's choice,#Execute associated command
#Display the options to the users
clear
echo "1. Date and time"
echo
echo "2. Directory listing"
echo
echo "3. Users information "
echo
echo "4. Current Directory"
echo
echo "Enter choice (1,2,3 or 4 ) :\n"
read choice
case $choice in
1) date;;
2) ls -l;;
3) who ;;
4) pwd ;;
*) echo wrong choice;;
esac
8/17/2019 ISC 357 Lab Manual
54/132
54 | P a g e
FLOW OF CONTROL STATEMENTS
The Bourne shell provides several flows of control statements. Select an item for further
information.
THE FOR STATEMENT
The for loop notation has the general form:
for var in list-of-words
do
commands
done
COMMANDS is a sequence of one or more commands separated by a new
line or ; (semicolon). The reserved words do and done must be preceded
by a new line or ; (semicolon). Small loops can be written on a single line.
For example:
for VAR in LIST;
do COMMANDS;
done
Examples
To take each argument in turn and see if that person is logged onto the system or not ?.
>cat snooper
# See if a number of people are logged in
for i in $*
do
if who | grep -s $i > /dev/nullthen
echo $i is logged in
else
echo $i not available
fi
done
For each username given as an argument a if statement is used to test if that person is logged on
and an appropriate message is then displayed.
8/17/2019 ISC 357 Lab Manual
55/132
55 | P a g e
THE WHILE AND UNTIL STATEMENTS
The while statement has the general form:
while command-list1
do
command-list2
done
The commands in COMMAND-LIST1 are executed; and if the exit status of the last command in
that list is 0 (zero), the commands in COMMAND-LIST2 are executed.
The sequence is repeated as long as the exit status of COMMAND-LIST1 is 0 (zero).
The until statement has the general form:until command-list1
do
command-list2
done
This is identical in function to the while command, except that the loop is executed as long as theexit status of COMMAND-LIST1 is non-zero. The exit status of a while/until command is the exit
status of the last command executed in COMMAND-LIST2. If no such command list is executed, awhile/until has an exit status of 0 (zero).
THE BREAK AND CONTINUE STATEMENTS
It is often necessary to handle exception conditions within loops. The statements break and
continue are used for this.
The break command terminates the execution of the innermost enclosing
loop, causing execution to resume after the nearest done statement. To
exit from n levels, use the command:
break N
This will cause execution to resume after the done N levels up.
The continue command causes execution to resume at the while, until or for statement whichbegins the loop containing the continue command. You can also specify an argument N|FR to
continue which will cause execution to continue at the N|FRth enclosing loop up.
Example s
To prompt for commands to run
while echo "Please enter command"
8/17/2019 ISC 357 Lab Manual
56/132
56 | P a g e
read response
do
case "$response" in
'done') break # no more commands
;;
"") continue # null command
;;
*) eval $response # do the command
;;
esac
done
This prompts the user to enter a command. While they enter a command or null string the script
continues to run. To stop the command the user enters done at the prompt.
Examples:
To show use of case statement
>cat Lab5_6
echo What kind of tree bears acorns\ ?
read responce
case $responce in
[Oo][Aa][Kk]) echo $responce is correct ;;
*) echo Sorry, response is wrong
esac
To show use of while statement
>cat Lab5_7
clear
echo What is the Capital of Saudi Arabia \?
read answer
while test $answer != Riyadh
do
echo No, Wrong please try again.
read answer
done
echo This is correct.
8/17/2019 ISC 357 Lab Manual
57/132
57 | P a g e
Example to show use of until statement
Accept the login name from the user
>cat Lab5_8
clear
echo "Please Enter the user login name: \n"read login_name
until who | grep $login_name
do
sleep 30
done
echo The user $login_name has logged in
#To show use of if statement
# Read three numbers and display largest>cat Lab5_9
clear
echo "Enter the first number :\n"
read num1
echo "Enter the second number :\n"
read num2
echo "Enter the third number :\n"
read num3
if test $num1 -gt $num2
then
if test $num1 -gt $num3
then
echo $num1 is the largest
else
echo $num3 is the largest
fielse
if test $num2 -gt $num3
then
echo $num2 is largest
else
echo $num3 is the largest
fi
fi
8/17/2019 ISC 357 Lab Manual
58/132
58 | P a g e
EXCERSICES
1. Run all the programs given above and observe the output of each program one by one.
2. Modify above shell script #File name lab5_2 to check the presence of target file before
copying.
Input and output for this program must be in the following format:
>./lab5_solution2
Please Enter Source filename: m1
Enter target file name: m2
Dear! Target file m2 already present
>./lab5_solution2
Please Enter Source filename: m2
Top Related