Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
317 views130 pages

OS Lab

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 130

Practical File

on
UGCA 1926 : Operating Systems Lab

Submitted By: Submitted To:


Sourav Mr. Daljeet Singh
BCA (Semester IV) Assistant Professor
Univ. Roll No:1933203
Class Roll No.:194016

(Session 2020 – 2021)


School of Information Technology
Apeejay Institute of Management &
Engineering Technical Campus, Jalandhar
Course Outcomes

CO1: Install & configure different operating systems.

CO2: Write programs/ scripts for different scheduling algorithms.

Program Outcomes

1. Basic knowledge: An ability to apply knowledge of basic


mathematics, science and domain knowledge to solve the
computational problems.

2. Discipline knowledge: An ability to apply discipline –specific


knowledge to solve core and/or applied computational problems.

3. Experiments and practice: An ability to plan and perform


experiments and practices and to use the results to solve
computational problems.

4. Tools Usage: Apply appropriate technologies and tools with an


understanding of limitations.

5. Profession and society: Demonstrate knowledge to assess


societal, health, safety, legal and cultural issues and the
consequent responsibilities relevant to professional practice.

6. Environment and sustainability: Understand the impact of


the computational solutions in societal and environmental
contexts, and demonstrate the knowledge and need for
sustainable development.

7. Ethics: Apply ethical principles and commit to professional


ethics and responsibilities and norms of the professional practice.
8. Individual and team work: Function effectively as an
individual, and as a member or leader in diverse/ multidisciplinary
teams.

9. Communication: An ability  to communicate effectively.

10. Life-long learning: Recognize the need for, and have the


preparation and ability to engage in independent and life-long
learning in the context of technological changes.
Practical 1

Aim: Installation of Windows Operating system

 Requirements:

 Processor: 1GHz or System on a Chip (SoC).

 Memory: 1GB for 32-bit or 2GB for 64-bit.

 Storage: 32GB for 64-bit or 32-bit.

 Graphics card: DirectX 9 or later with WDDM 1.0 driver.

 Display: 800x600.

Change boot order on firmware


It's also important to make sure that the computer can boot from a
USB flash drive. If this is not the case, you'll need to change the Basic
Input/Output System (BIOS) or Unified Extensible Firmware Interface
(UEFI) on the motherboard.

Change boot order using UEFI


On devices already running Windows 10 or Windows 8.1, you can
access the settings to change the boot order from within the desktop
environment.

UEFI settings on Windows 10

To change the UEFI boot settings on Windows 10, use these steps:

1. Open Settings.
2. Click on Update & Security.

3. Click on Recovery.

4. Under the "Advanced Startup" section, click the Restart


now button.

5. Click the Troubleshoot button.
6. Click on Advanced options.

7. Click the UEFI Firmware Settings option.


8. Click the Restart button.
9. While in the motherboard firmware settings, open the Boot page.

10. Set the boot order to start from the USB flash drive with the
Windows 10 installation files.
Save the changes.
After you complete the steps, the computer should now be able to
start from a USB bootable media.

Once you went through the preparation instructions, the clean install of
Windows 10 is actually a straightforward process.

Warning: This is another friendly reminder that this process will erase


everything on the computer. It's always recommended to make a
temporary full backup of your PC before proceeding.

To do a clean installation of Windows 10, use these steps:


1. Start the device with Windows 10 USB media.
2. On prompt, press any key to boot from the device.
3. On the "Windows Setup," click the Next button.

Quick tip: If your language, time and currency, and keyboard are different
from the default selections, make sure to select the correct settings before
continuing.
4. Click the Install now button.
5. If you're doing a reinstallation, click the I don't have a product
key option to continue (assuming that your device was already activated).
Otherwise, in the case that this is your first time installing Windows 10, enter
the product key.
6. Click the Next button.
7. Select the edition of Windows 10 (If applicable).
Quick note: This selection must match the edition that the product key
activates. If you don't select the correct edition, Windows 10 won't activate,
and you'll have to redo the entire process one more time.
8. Click the Next button.
9. Select the I accept the license terms option to continue.
10. Click the Next button.
11. Click the Custom: Install Windows only (Advanced) option to continue
with a clean installation.
12. Select the partition with the current installation (usually "Drive 0"), and
click the Delete button.
Quick tip: If "Drive 0" has multiple partitions, you have to select and delete
each partition to allow the setup to use the entire hard drive for the new clean
installation. The Windows 10 setup will create the required partitions
automatically during the process. Also, it's not necessary to delete the
partitions on secondary drives.
13. Click the Yes button.
14. Select the empty drive (Drive 0 Unallocated Space).
15. Click the Next button.
Once you complete the steps, the setup will install a fresh copy of Windows 10
on the computer.
Practical 2
Aim: Installation of linux operating system

Once you download the ISO file, you will have to burn it on DVD or the
easy way, copying it on a USB stick using a program called Universal
USB installer, you can download this program from google

After downloading the application, open it and choose from the list the
distro you want to install; in our case, we will select Linux mint.

Make sure that you put your memory stick on the computer and click
next and wait till the copying process is finished.
Now Finally we click create to create bootable USB
And now you can boot with this memory stick.

Then Restart your PC and go to BIOS settings and select boot options
and make sure that the USB is the first option, then save your BIOS
settings and reboot.
Then it will show the installation screen, press Enter, and it will load the
live CD content.
Now the desktop should appear like that:
Click install Linux Mint.

Then choose the language used for installation.


Then choose the installation type, and TAKE CARE if you are installing
Linux on a disk that contains other operating systems, you MUST select
the option called something else.

If you are installing it on a new disk, choose the option Erase disk.

Linux requires two partitions to work, the root partition and the swap


partition.

Now we will create them by clicking the plus button and choose about 12
GB or more as you need but not less than that for the root partition and
choose mount type as / which stands for root and of course format will
be Ext4.
Now we create a swap partition, choose the remaining free space and
click the plus button and choose the swap area as shown:
Then Create the swap area:
Then click install now and agree about writing changes to disk:
Now you choose the time zone and click continue the choose the
language:
Now you write your username and password and click continue:
Finally, the installation started:
After finishing the installation, it will prompt you to reboot the machine
and remove the installation media, whether it is a DVD or USB.
Practical 3
Aim Dual boot 2 operating systems

Follow the steps below to install Linux Mint in dual boot with Windows:

Go to Linux Mint website and download ISO file. This ISO file is the disk image that you can
burn to a USB or DVD. 

There are several versions of Linux Mint available. The default is Cinnamon. If your computer
supports 64 bit, go with 64 bit Linux Mint 19.3 Cinnamon. If you know about other desktop
environments, you can make your mind and choose whichever Mint version you want.

Once you have downloaded the Linux Mint ISO, you need a tool to write the image to a disk. I
recommend using a free tool called Universal USB Installer in Windows:

It’s an executable exe file. Just double click on it to run the software and browse it to the ISO.
Make sure that you have your USB key plugged in:
This is where you have to be cautious. If you have multiple partitions (not the recovery ones),
you can either use one of them or create a new partition from an existing partition. Your existing
data will be safe if you have enough free space. Typically, you install Linux in under 10 Gb,
however, if disk space if not a concern, I advise using 30-40Gb at least. This way you can have
more space at your disposal for downloading and keeping various files.

In Windows 10, go to start menu and type ‘partition’. This will bring up Disk Management
utility.  Now carefully select the disk in which you’ll make some free space by shrinking the
volume:
In my case, I only had the C Drive with 223Gb of space on it. So I shrunk it to make 110Gb of
free partition on it. I recommend watch the video to see the exact steps you need more hint.

Plug the live USB or disk into the computer and restart the computer. While booting the
computer press F10 or F12 function key (defers fom computer to computer) to go to the boot
menu. Now, choose the option to boot from USB or Removable Media.

Important Note: If your computer came with Windows 8 or Windows 8.1 and you upgraded
your system to Windows 10, you may have to disable secure boot. Most modern system with
Windows 10 should not need this step, especially with Linux Mint or Ubuntu.

It takes some time to boot from the live USB or disk. Have some patience. Once it boots in to
live disk, you’ll be provided to Try Linux Mint or Install Linux Mint. Even if you choose to try
it, you can find the install option on the desktop:
In next few screens, you’ll be asked to choose the language of the operating system. It will then
do some checks on available space, battery and Internet connection.
This is the most important part of the whole installation. Where to install Linux Mint?

If you see the option to Install Linux Mint alongside Windows, you can select that. Linux Mint
will handle things on its own. If you do that, skip step 5 and step 6.

But as mentioned before, I prefer separate partitions for Windows and Linux. Windows is
already installed here, we’ll prepare a new partition for Linux Mint. In the Installation Type
window, choose Something Else:
Since you already created a new partition in Windows, it’s time to install Linux Mint on it. Now,
there are several ways to do it. But here, I’ll show you my favorite way and that is to have a
Root, a Swap and a Home.

Create a root partition first. Choose the free space available and click on +.
Here, choose the size of the root. Root is like your C drive in Windows. Installed software,
updates and other system files are under this root partition. Home partition is for your personal
documents, music, downloads etc.

If you have total 100 GB at disposal, give 30 GB to root. In any case, don’t give it less than 15
GB because if root runs out of space, your system will slow down and you’ll run into issues.

I opted to have 20 GB, choose ext4 file system, and mount point as / (i.e. root):
 RAM less than 2 GB: Swap should be double the size of RAM
 RAM between 2 to 4 GB: Swap should be RAM size + 2 GB
 RAM between 6 GB to 8 GB: Swap should be size of RAM
 RAM more than 8 GB: Swap should be half the size of RAM or less

Don’t spend too much time thinking about swap. It is helpful for systems with less memory. For
system with more than 8 GB of RAM and SSD, the less the swap, the better it is.

Newer version of Linux Mint utilize Swap file. It creates a special file under root and utilizes it
as swap area. You can have both swap partition and swap file in a system.
The next step is to create Home. Try to allocate the maximum size to Home because this is
where you’ll be downloading and keeping the files.
Once you have created Root, Swap and Home partitions, click on Install Now button.
Technically, you have crossed the main hurdle if you reached this point successfully. Now you
will be taken through a number of screens to select options like keyboard layout, login
credentials etc. You don’t need to be a genius to figure out what to do here afterward. I have
attached screenshots for reference purpose here.
Once the installation is over, you will be presented with the option to keep trying live version or
to restart the system.
Practical 4

Aim: Implementation of FCFS Scheduling algorithm

First Come First Serve (FCFS) is an operating system scheduling


algorithm that automatically executes queued requests and processes
in order of their arrival. It is the easiest and simplest CPU scheduling
algorithm. In this type of algorithm, processes which requests the CPU
first get the CPU allocation first. This is managed with a FIFO queue.
The full form of FCFS is First Come First Serve.

As the process enters the ready queue, its PCB (Process Control Block)
is linked with the tail of the queue and, when the CPU becomes free, it
should be assigned to the process at the beginning of the queue.

A real-life example of the FCFS method is buying a movie ticket on the


ticket counter. In this scheduling algorithm, a person is served
according to the queue manner. The person who arrives first in the
queue first buys the ticket and then the next one. This will continue
until the last person in the queue purchases the ticket. Using this
algorithm, the CPU process works in a similar manner.

Here is an example of five processes arriving at different times. Each


process has a different burst time.

Process Burst time

P1 6
P2 3

P3 8

P4 3

P5 4

Using the FCFS scheduling algorithm, these processes are handled


as follows.

Step 0) The process begins with P4 which has arrival time 0

Step 1) At time=1, P3 arrives. P4 is still executing. Hence, P3 is kept


in a queue.
Process Burst time

P1 6

P2 3

P3 8

P4 3

P5 4
Step 2) At time= 2, P1 arrives which is kept in the queue.

Process Burst time

P1 6

P2 3

P3 8

P4 3

P5 4
Step 3) At time=3, P4 process completes its execution.

Step 4) At time=4, P3, which is first in the queue, starts execution.

Process Burst time

P1 6

P2 3

P3 8
P4 3

P5 4

Step 5) At time =5, P2 arrives, and it is kept in a queue.

Process Burst time

P1 6
P2 3

P3 8

P4 3

P5 4

Step 6) At time 11, P3 completes its execution.


Step 7) At time=11, P1 starts execution. It has a burst time of 6. It
completes execution at time interval 17

Step 8) At time=17, P5 starts execution. It has a burst time of 4. It


completes execution at time=21

 Step 9) At time=21, P2 starts execution. It has a burst time of 2.


It completes execution at time interval 23

Step 10) Let's calculate the average waiting time for above example.
Waiting time = Start time - Arrival time

P4 = 0-0 = 0

P3 = 3-1 = 2

PI = 11-2 = 9

P5= 17-4 = 13

P2= 21-5= 16

Average Waiting Time

= 40/5= 8

Advantages of FCFS

Here, are pros/benefits of using FCFS scheduling algorithm:

 The simplest form of a CPU scheduling algorithm


 Easy to program
 First come first served

Disadvantages of FCFS

Here, are cons/ drawbacks of using FCFS scheduling algorithm:

 It is a Non-Preemptive CPU scheduling algorithm, so after the


process has been allocated to the CPU, it will never release the
CPU until it finishes executing.
 The Average Waiting Time is high.
 Short processes that are at the back of the queue have to wait
for the long process at the front to finish.
 Not an ideal technique for time-sharing systems.
 Because of its simplicity, FCFS is not very efficient.
Practical 4
Shortest Job First (SJF) is an algorithm in which the process having
the smallest execution time is chosen for the next execution. This
scheduling method can be preemptive or non-preemptive. It
significantly reduces the average waiting time for other processes
awaiting execution. The full form of SJF is Shortest Job First.

There are basically two types of SJF methods:

 Non-Preemptive SJF
 Preemptive SJF

Characteristics of SJF Scheduling

 It is associated with each job as a unit of time to complete.


 It is associated with each job as a unit of time to complete.
 This algorithm method is helpful for batch-type processing, where waiting for jobs to
complete is not critical.
 It can improve process throughput by making sure that shorter jobs are executed first,
hence possibly have a short turnaround time.
 It improves job output by offering shorter jobs, which should be executed first, which
mostly have a shorter turnaround time.

In non-preemptive scheduling, once the CPU cycle is allocated to process, the process holds it
till it reaches a waiting state or terminated.

Consider the following five processes each having its own unique
burst time and arrival time.

Process Queue Burst time


P1 6

P2 2

P3 8

P4 3

P5 4
Step 0) At time=0, P4 arrives and starts execution.

Step 1) At time= 1, Process P3 arrives. But, P4 still needs 2 execution


units to complete. It will continue execution.

Step 2) At time =2, process P1 arrives and is added to the waiting
queue. P4 will continue execution.

Step 3) At time = 3, process P4 will finish its execution. The burst time
of P3 and P1 is compared. Process P1 is executed because its burst
time is less compared to P3.
Step 4) At time = 4, process P5 arrives and is added to the waiting
queue. P1 will continue execution.

Step 5) At time = 5, process P2 arrives and is added to the waiting


queue. P1 will continue execution.

Step 6) At time = 9, process P1 will finish its execution. The burst time
of P3, P5, and P2 is compared. Process P2 is executed because its burst
time is the lowest.
Step 7) At time=10, P2 is executing and P3 and P5 are in the waiting
queue.

Step 8) At time = 11, process P2 will finish its execution. The burst
time of P3 and P5 is compared. Process P5 is executed because its
burst time is lower.

Step 9) At time = 15, process P5 will finish its execution.


Step 10) At time = 23, process P3 will finish its execution.

Step 11) Let's calculate the average waiting time for above example.

Wait time

P4= 0-0=0

P1= 3-2=1

P2= 9-5=4

P5= 11-4=7

P3= 15-1=14

Average Waiting Time= 0+1+4+7+14/5 = 26/5 = 5.2


Preemptive SJF

In Preemptive SJF Scheduling, jobs are put into the ready queue as
they come. A process with shortest burst time begins execution. If a
process with even a shorter burst time arrives, the current process is
removed or preempted from execution, and the shorter job is
allocated CPU cycle.

Consider the following five process:

Process Queue Burst time

P1 6

P2 2

P3 8
P4 3

P5 4

Step 0) At time=0, P4 arrives and starts execution.

Process Queue Burst time

P1 6

P2 2
P3 8

P4 3

P5 4

Step 1) At time= 1, Process P3 arrives. But, P4 has a shorter burst time.
It will continue execution.
Step 2) At time = 2, process P1 arrives with burst time = 6. The burst
time is more than that of P4. Hence, P4 will continue execution.

Step 3) At time = 3, process P4 will finish its execution. The burst time
of P3 and P1 is compared. Process P1 is executed because its burst
time is lower.

Step 4) At time = 4, process P5 will arrive. The burst time of P3, P5,
and P1 is compared. Process P5 is executed because its burst time is
lowest. Process P1 is preempted.
Process Queue Burst time

P1 5 out of 6 is remaining

P2 2

P3 8

P4 3

P5 4
Step 5) At time = 5, process P2 will arrive. The burst time of P1, P2, P3,
and P5 is compared. Process P2 is executed because its burst time is
least. Process P5 is preempted.

Process Queue Burst time

P1 5 out of 6 is remaining

P2 2

P3 8
P4 3

P5 3 out of 4 is remaining

Step 6) At time =6, P2 is executing.

Step 7) At time =7, P2 finishes its execution. The burst time of P1, P3,
and P5 is compared. Process P5 is executed because its burst time is
lesser.
Process Queue Burst time

P1 5 out of 6 is remaining

P2 2

P3 8

P4 3

P5 3 out of 4 is remaining
Step 8) At time =10, P5 will finish its execution. The burst time of P1
and P3 is compared. Process P1 is executed because its burst time is
less.

Step 9) At time =15, P1 finishes its execution. P3 is the only process
left. It will start execution.

Step 10) At time =23, P3 finishes its execution.


Step 11) Let's calculate the average waiting time for above example.

Wait time

P4= 0-0=0

P1= (3-2) + 6 =7

P2= 5-5 = 0

P5= 4-4+2 =2

P3= 15-1 = 14

Average Waiting Time = 0+7+0+2+14/5 = 23/5 =4.6


Practical 6

The name of this algorithm comes from the round-robin principle,


where each person gets an equal share of something in turns. It is the
oldest, simplest scheduling algorithm, which is mostly used for
multitasking.

In Round-robin scheduling, each ready task runs turn by turn only in a


cyclic queue for a limited time slice. This algorithm also offers
starvation free execution of processes.

 Round robin is a pre-emptive algorithm


 The CPU is shifted to the next process after fixed interval time,
which is called time quantum/time slice.
 The process that is preempted is added to the end of the queue.
 Round robin is a hybrid model which is clock-driven
 Time slice should be minimum, which is assigned for a specific
task that needs to be processed. However, it may differ OS to OS.
 It is a real time algorithm which responds to the event within a
specific time limit.
 Round robin is one of the oldest, fairest, and easiest algorithm.
 Widely used scheduling method in traditional OS.

Example of Round-robin Scheduling

Consider this following three processes

Process Queue
P1

P2

P3

Step 1) The execution begins with process P1, which has burst time 4.
Here, every process executes for 2 seconds. P2 and P3 are still in the
waiting queue.
Step 2) At time =2, P1 is added to the end of the Queue and P2 starts
executing

Step 3) At time=4 , P2 is preempted and add at the end of the queue.
P3 starts executing.
Step 4) At time=6 , P3 is preempted and add at the end of the queue.
P1 starts executing.

Step 5) At time=8 , P1 has a burst time of 4. It has completed


execution. P2 starts execution
Step 6) P2 has a burst time of 3. It has already executed for 2 interval.
At time=9, P2 completes execution. Then, P3 starts execution till it
completes.

Step 7) Let's calculate the average waiting time for above example.

Wait time
P1= 0+ 4= 4

P2= 2+4= 6

P3= 4+3= 7
Practical 7
The default editor that comes with the UNIX operating system is
called vi (visual editor). Using vi editor, we can edit an existing file
or create a new file from scratch. we can also use this editor to just
read a text file.

 Command Mode: When vi starts up, it is in Command Mode.


This mode is where vi interprets any characters we type as
commands and thus does not display them in the window. This
mode allows us to move through a file, and to delete, copy, or
paste a piece of text.
To enter into Command Mode from any other mode, it
requires pressing the [Esc] key. If we press [Esc] when we are
already in Command Mode, then vi will beep or flash the
screen.
 Insert mode: This mode enables you to insert text into the file.
Everything that’s typed in this mode is interpreted as input and
finally, it is put in the file. The vi always starts in command
mode. To enter text, you must be in insert mode. To come in
insert mode you simply type i. To get out of insert mode, press
the Esc key, which will put you back into command mode.
 Last Line Mode(Escape Mode): Line Mode is invoked by
typing a colon [:], while vi is in Command Mode. The cursor
will jump to the last line of the screen and vi will wait for a
command. This mode enables you to perform tasks such as
saving files, executing commands.

There are following way you can start using vi editor :

Commands and their Description


 vi filename:  Creates a new file if it already not exist, otherwise
opens existing file.
 vi -R filename  : Opens an existing file in read only mode.
 view filename  : Opens an existing file in read only mode.
Moving within a File(Navigation):
To move around within a file without affecting text must be in
command mode (press Esc twice). Here are some of the commands
can be used to move around one character at a time.
Commands and their Description
 k  : Moves the cursor up one line.
 j  : Moves the cursor down one line.
 h  : Moves the cursor to the left one character position.
 l  : Moves the cursor to the right one character position.
 0 or |  : Positions cursor at beginning of line.
 $  : Positions cursor at end of line.
 W  : Positions cursor to the next word.
 B  : Positions cursor to previous word.
 (  : Positions cursor to beginning of current sentence.
 )  : Positions cursor to beginning of next sentence.
 H  : Move to top of screen.
 nH  : Moves to nth line from the top of the screen.
 M  : Move to middle of screen.
 L  : Move to bottom of screen.
 nL  : Moves to nth line from the bottom of the screen.
 colon along with x  : Colon followed by a number would
position the cursor on line number represented by x.
Control Commands(Scrolling): There are following useful
commands which can used along with Control Key:
Commands and their Description:
 CTRL+d  : Move forward 1/2 screen.
 CTRL+f  : Move forward one full screen.
 CTRL+u  : Move backward 1/2 screen.
 CTRL+b  : Move backward one full screen.
 CTRL+e  : Moves screen up one line.
 CTRL+y  : Moves screen down one line.
 CTRL+u  : Moves screen up 1/2 page.
 CTRL+d  : Moves screen down 1/2 page.
 CTRL+b  : Moves screen up one page.
 CTRL+f  : Moves screen down one page.
 CTRL+I  : Redraws screen.
Editing and inserting in Files(Entering and Replacing Text): To
edit the file, we need to be in the insert mode. There are many ways
to enter insert mode from the command mode.
 i  : Inserts text before current cursor location.
 I  : Inserts text at beginning of current line.
 a  : Inserts text after current cursor location.
 A  : Inserts text at end of current line.
 o  : Creates a new line for text entry below cursor location.
 O  : Creates a new line for text entry above cursor location.
 r  : Replace single character under the cursor with the next
character typed.
 R  : Replaces text from the cursor to right.
 s  : Replaces single character under the cursor with any number
of characters.
 S  :Replaces entire line.
Deleting Characters: Here is the list of important commands which
can be used to delete characters and lines in an opened file.
 X  Uppercase: Deletes the character before the cursor location.
 x  Lowercase : Deletes the character at the cursor location.
 Dw  : Deletes from the current cursor location to the next word.
 d^  : Deletes from current cursor position to the beginning of
the line.
 d$  : Deletes from current cursor position to the end of the line.
 Dd  : Deletes the line the cursor is on.
Copy and Past Commands: Copy lines or words from one place
and paste them on another place by using the following
commands.
 Yy  : Copies the current line.
 9yy  : Yank current line and 9 lines below.
 p  : Puts the copied text after the cursor.
 P  : Puts the yanked text before the cursor.
Save and Exit Commands of the ex Mode : Need to
press [Esc] key followed by the colon (:) before typing the following
commands:

 q  : Quit
 q!  : Quit without saving changes i.e. discard changes.
 r fileName  : Read data from file called fileName.
 wq  : Write and quit (save and exit).
 w fileName  : Write to file called fileName (save as).
 w! fileName  : Overwrite to file called fileName (save as
forcefully).
 !cmd  : Runs shell commands and returns to Command mode.
Searching and Replacing in (ex Mode): vi also has powerful
search and replace capabilities. The formal syntax for searching is:
:s/string
Practical 8

Command Description

logout log out of a Linux termin

Note, on a Linux workstation you will need to exit the Desktop


Environment instead.

Files and Directories

These commands allow you to create directories and handle files.

Command Description

cat concatenate and print data

lpr spool file for line printing


Command Description

cd change current directory

lprm, cancel remove jobs from line printer queue

chgrp change file group

ls list and generate statistics for files

chmod change file mode

mkdir make a new directory


Command Description

cp copy file data

more, page display file data at your terminal

Command Description

file determine file type

mv move or rename files

find find files


Command Description

pwd print working directory

grep search file for regular expression

rm, rmdir remove (unlink) files or directories

head give first few lines

tail print last lines from file

just text justification program


Command Description

touch update access and modification tim

lpq spool queue examination program

File Editors

Editors are used to create and amend files.

Command Description

emacs GNU project Emacs

xemacs emacs with mouse action


Command Description

ex, edit line editor

Command Description

pico easy text editor for vdus

pluma Mate GUI text editor

gedit GNOME text editor

vi, vim standard text editor


Vi, pico and emacs are screen-based editors which run on a vdu or in
a workstations terminal emulation
window; pluma, gedit and xemacs are graphical user interface (GUI)
based editors with cut and paste and mouse-controlled cursor
positioning.

Manipulating data

The contents of files can be compared and altered with the following
commands.

Command Description

awk pattern scanning and processing lan

perl data manipulation language

cmp compare the contents of two files

paste merge file data


Command Description

comm compare sorted data

sed stream text editor

cut cut out selected fields of each line o

sort sort file data

diff differential file comparator

Command Description
Command Description

split split file into smaller files

expand, unexpand expand tabs to spaces, and vice vers

tr translate characters

gawk pattern scanning and processing lan

uniq report repeated lines in a file

join join files on some common field


Command Description

look find lines in sorted data

wc count words, lines, and characters


Practical 9

Aim: Shell scripting using variables

A variable is nothing more than a pointer to the actual data. The shell
enables you to create, assign, and delete variables.
Variable Names
The name of a variable can contain only letters (a to z or A to Z),
numbers ( 0 to 9) or the underscore character ( _).
By convention, Unix shell variables will have their names in
UPPERCASE.
The following examples are valid variable names −
_ALI
TOKEN_A
VAR_1
VAR_2
Following are the examples of invalid variable names −
2_VAR
-VARIABLE
VAR1-VAR2
VAR_A!
The reason you cannot use other characters such as !, *, or - is that
these characters have a special meaning for the shell.

Defining Variables
Variables are defined as follows −
variable_name=variable_value
For example −

NAME="Zara Ali"

The above example defines the variable NAME and assigns the value
"Zara Ali" to it. Variables of this type are called scalar variables. A
scalar variable can hold only one value at a time.
Shell enables you to store any value you want in a variable. For
example −

VAR1="Zara Ali"
VAR2=100

Accessing Values
To access the value stored in a variable, prefix its name with the dollar
sign ($) −
For example, the following script will access the value of defined
variable NAME and print it on STDOUT −

#!/bin/sh

NAME="Zara Ali"
echo $NAME

The above script will produce the following value −


Zara Ali

Read-only Variables
Shell provides a way to mark variables as read-only by using the read-
only command. After a variable is marked read-only, its value cannot
be changed.
For example, the following script generates an error while trying to
change the value of NAME −

#!/bin/sh

NAME="Zara Ali"
readonly NAME
NAME="Qadiri"

The above script will generate the following result −


/bin/sh: NAME: This variable is read only.
Unsetting Variables
Unsetting or deleting a variable directs the shell to remove the
variable from the list of variables that it tracks. Once you unset a
variable, you cannot access the stored value in the variable.
Following is the syntax to unset a defined variable using
the unset command −
unset variable_name
The above command unsets the value of a defined variable. Here is a
simple example that demonstrates how the command works −

#!/bin/sh

NAME="Zara Ali"
unset NAME
echo $NAME

The above example does not print anything. You cannot use the
unset command to unset variables that are marked readonly.

Variable Types
When a shell is running, three main types of variables are present −
 Local Variables − A local variable is a variable that is present
within the current instance of the shell. It is not available to
programs that are started by the shell. They are set at the
command prompt.
 Environment Variables − An environment variable is available
to any child process of the shell. Some programs need
environment variables in order to function correctly. Usually, a
shell script defines only those environment variables that are
needed by the programs that it runs.
 Shell Variables − A shell variable is a special variable that is set
by the shell and is required by the shell in order to function
correctly. Some of these variables are environment variables
whereas others are local variables.
Practical 10

The Bourne shell syntax provides basic input with very little effort.

#!/bin/sh

printf "What is your name? -> "

read NAME

echo "Hello, $NAME. Nice to meet you."


You will notice two things about this script. The first is that it
introduces the printf command. This command is used because,
unlike echo, the printf command does not automatically add a newline
to the end of the line of output. This behavior is useful when you need
to use multiple lines of code to output a single line of text. It also just
happens to be handy for prompts.

Note: In most operating systems, you can tell echo to suppress the


newline. However, the syntax for doing so varies. Thus, printf is
recommended for printing prompts. See Designing Scripts for Cross-
Platform Deployment for more information and other alternatives.
The second thing you'll notice is the read command. This command
takes a line of input and separates it into a series of arguments. Each
of these arguments is assigned to the variables in the read statement
in the order of appearance. Any additional input fields are appended
to the last entry.
You can modify the behavior of the read command by modifying the
shell variable IFS (short for internal field separators). The default
behavior is to split inputs everywhere there is a space, tab, or newline.
By changing this variable, you can make the shell split the input fields
by tabs, newlines, semicolons, or even the letter 'q'. This change in
behavior is demonstrated in the following example:

#!/bin/sh

printf "Type three numbers separated by 'q'. -> "

IFS="q"

read NUMBER1 NUMBER2 NUMBER3

echo "You said: $NUMBER1, $NUMBER2, $NUMBER3"


If, for example, you run this script and enter 1q3q57q65, the script
replies with You said: 1, 3, 57q65. The third value
contains 57q65 because only three values are requested in the read
statement.
Note: The read statement always stops reading at the first newline
encountered. Thus, if you set IFS to a newline, you cannot read
multiple entries with a single read statement.
Warning: Changing IFS may cause unexpected consequences for
variable expansion. For more information, see Variable Expansion
and Field Separators.
But what if you don’t know how many parameters the user will
specify? Obviously, a single read statement cannot split the input up
into an arbitrary number of variables, and the Bourne shell does not
contain true arrays. Fortunately, the eval builtin can be used to
simulate an array using multiple shell variables. This technique is
described in Using the eval Builtin for Data Structures, Arrays, and
Indirection.
Alternatively, you can use the for statement, which splits a single
variable into multiple pieces based on the internal field separators.
This statement is described in The for Statement.
C Shell Note: In the C shell, the syntax for reading is completely
different. The following script is the C shell equivalent of the script
earlier in this section:

printf "What is your name? -> "

set NAME = "$<"

echo "Hello, $NAME. Nice to meet you."


The C shell does not provide a way to read multiple values in a single
command, though you can approximate this with careful use of sed as
described in Regular Expressions Unfettered or cut. For example:

#!/bin/csh

printf "Type three numbers separated by 'q'. -> "

set LINE = "$<"

set NUMBER1 = `echo "$LINE" | cut -f 1 -d 'q'`

set NUMBER2 = `echo "$LINE" | cut -f 2 -d 'q'`

set NUMBER3 = `echo "$LINE" | cut -f 3 -d 'q'`


echo "You said: $NUMBER1, $NUMBER2, $NUMBER3"
Practical 11

We cannot use bash variables without having the proper information


(syntax, data types, types, working) about it, so, let's go throughout
this brief tutorial for having the appropriate overview of Bash
Variables.

At first, know the syntax.

Syntax:

1. Variable_name=value  

Rules Set for Defining Bash Variables:

1. Prefix the variable name with dollar ($) sign while reading or

printing a variable.

2. Leave off the dollar sign ($) while setting a variable with any

value.

3. A variable name may be alphanumeric, or it may be written with

an underscore (_).
4. A variable name is case-sensitive: x and X are considered as two

different variables.

5. variable name can be written either in UPPER_CASE or

LOWER_CASE letters or mixture of both as you want.

6. A variable can be placed at anywhere in a Bash Script or on the

command line, because on runtime, Bash will replace it with its

assigned value. It became possible because of doing substitution

before running the command.

7. There should not be whitespace on either side of the equal sign

(=) between the variable name and its value. Following are some

example of Invalid Variables having whitespaces (denoted by

dots ...) between them as given below:

var1=...variable1
var2...=variable2

var3...=...variable3

8. There is no need of using any quotes, either single or double, to

define a variable with single character value such

as var1=variable. To input multiple words or String as a single

item in a variable, then make use of quotes for enclosing your

content in that variable.

o Single Quote ('') helps to treat every character.

o Double Quote ("") helps to do the substitution.

Data Types

In the formal programming languages, you have to define the data


type of any variable at the time of variable declaration. For example:

1. int year=2012  

2. char comp_name='jtp'  
But in case of Bash, you don't have to define the data type of any
variable at the time of variable declaration. Bash variables
are untyped, which means just type the variable name by assigning its
value, and it will automatically consider that data type.

Such that if you assign any numeric value to the variable, it will work
as integer and if you assign a character value to the variable, then it
will be String.

1. year=2012  

2. comp_name=jtp  

using echo command, read them by assigning $ sign before their


name such as

echo $year
echo $name

Types of Bash Variables

There are two types of variables in a shell or any UNIX system.

1. System-Defined Variables

2. User-Defined Variables

1. System-Defined Variables: These are the pre-defined variables as


they are created and maintained by the LINUX operating system itself.
Their standard convention is that generally they are defined in capital
letters, i.e., UPPER_CASE. So whenever you see a variable defined in
upper cases, most likely, they are the system-defined variables.

These are the following System-defined variables as given below:

1. BASH represents the Shell Name.

Example:

1. BASH=/usr/bin/bash  

2. BASH_VERSION specifies the shell version which the Bash holds.

Example:

1. BASH_VERSION=4.2.46(2)  

3. COLUMNS specify the no. of columns for our screen.

Example:

1. COLUMNS=80  

4. HOME specifies the home directory for the user.

Example:

1. HOME=/home/jatpoint  

5. LOGNAME specifies the logging user name.


Example:

1. LOGNAME=javatpoint  

6. OSTYPE tells the type of OS.

Example:

1. OSTYPE=linux-gnu  

7. PWD represents the current working directory.

Example:

1. PWD=/home/javatpoint  

8. USERNAME specifies the name of currently logged in user.

Example:

1. USERNAME=javatpoint  

To know the list of these variables in your system, type the


commands set, env, and printenv on the command line terminal as
follows:

      

1. Typing the set command.

Output:
2. Typing the env command

   

Output:
3. Typing the printenv command

Output:
Let's call these variables through Bash Shell. Following are the given
steps:

Step 1: Create a script named by Bash_sdvar and type the following


code on the Bash Console as follows:

1. #! /bin/bash  

2. # Bash System-defined Variables  

3. echo $HOME # Home Directory  

4. echo $PWD # current working directory  
5. echo $BASH # Bash shell name  

6. echo $BASH_VERSION # Bash shell Version  

7. echo $LOGNAME # Name of the Login User  

8. echo $OSTYPE # Type of OS  

Step 2. Look at the Bash Console given below:

Step 3. Save and execute the script. It will show the output as you can
see in the figure given below.

Output:
2. User-defined Variables: These variables are created and
maintained by the user. Generally, these types of variables are defined
in LOWER_CASES. There is not any strict rule to write these variables in
lower-cases. We can write them in upper-cases also.

Let's create a Bash Script to define these variables. Follow the given
steps given below:

Step 1. Create a script named by Bash_udvar and type the following


code on Bash Console:

1. #! /bin/bash  

2. # User-Defined Variables   

3. name=Peter  

4. ROLL_NO=5245325  
5. echo "The student name is $name and his Roll number is $ROLL_

NO."  

Step 2. See the code on Bash Console.

Step 3. Save and execute the Script.

Output:
Practical 12

The following arithmetic operators are supported by Bourne Shell.


Assume variable a holds 10 and variable b holds 20 then −

Operator Descripti

+ (Addition) Adds values on either side of the operator

- (Subtraction) Subtracts right hand operand from left han

* (Multiplication) Multiplies values on either side of the oper

/ (Division) Divides left hand operand by right hand op

% (Modulus) Divides left hand operand by right hand op


= (Assignment) Assigns right operand in left operand

== (Equality) Compares two numbers, if both are same t

!= (Not Equality) Compares two numbers, if both are differen

It is very important to understand that all the conditional expressions


should be inside square braces with spaces around them, for
example [ $a == $b ] is correct whereas, [$a==$b] is incorrect.
All the arithmetical calculations are done using long integers.

Example
Here is an example which uses all the arithmetic operators −

#!/bin/sh

a=10
b=20

val=`expr $a + $b`
echo "a + b : $val"

val=`expr $a - $b`
echo "a - b : $val"
val=`expr $a \* $b`
echo "a * b : $val"

val=`expr $b / $a`
echo "b / a : $val"

val=`expr $b % $a`
echo "b % a : $val"

if [ $a == $b ]
then
echo "a is equal to b"
fi

if [ $a != $b ]
then
echo "a is not equal to b"
fi

The above script will produce the following result −


a + b : 30
a - b : -10
a * b : 200
b/a:2
b%a:0
a is not equal to b
The following points need to be considered when using the
Arithmetic Operators −
 There must be spaces between the operators and the
expressions. For example, 2+2 is not correct; it should be written
as 2 + 2.
 Complete expression should be enclosed between ‘ ‘, called the
inverted commas.
 You should use \ on the * symbol for multiplication.
Practical 13

Conditional Statements: There are total 5 conditional statements


which can be used in bash programming
1. if statement
2. if-else statement
3. if..elif..else..fi statement (Else If ladder)
4. if..then..else..if..then..fi..fi..(Nested if)
5. switch statement
Their description with syntax is as follows:

if statement
This block will process if specified condition is true.
Syntax:
if [ expression ]
then
statement
fi
if-else statement
If specified condition is not true in if part then else part will be
execute.
Syntax
if [ expression ]
then
statement1
else
statement2
fi
if..elif..else..fi statement (Else If ladder)
To use multiple conditions in one if-else block, then elif keyword is
used in shell. If expression1 is true then it executes statement 1 and
2, and this process continues. If none of the condition is true then it
processes else part.
Syntax

if [ expression1 ]
then
statement1
statement2
.
.
elif [ expression2 ]
then
statement3
statement4
.
.
else
statement5
fi
if..then..else..if..then..fi..fi..(Nested if)
Nested if-else block can be used when, one condition is satisfies
then it again checks another condition. In the syntax, if expression1
is false then it processes else part, and again expression2 will be
check.
Syntax:
if [ expression1 ]
then
statement1
statement2
.
else
if [ expression2 ]
then
statement3
.
fi
fi
switch statement
case statement works as a switch statement if specified value match
with the pattern then it will execute a block of that particular
pattern
When a match is found all of the associated statements until the
double semicolon (;;) is executed.
A case will be terminated when the last command is executed.
If there is no match, the exit status of the case is zero.
Syntax:
case in
Pattern 1) Statement 1;;
Pattern n) Statement n;;
esac
Example Programs
Example 1:
Implementing if statement

#Initializing two variables

a=10
b=20

  

#Check whether they are equal

if [ $a == $b ]

then

    echo "a is equal to b"

fi

  

#Check whether they are not equal


if [ $a != $b ]

then

    echo "a is not equal to b"

fi

Output
$bash -f main.sh

a is not equal to b

Example 2:
Implementing if.else statement

#Initializing two variables

a=20
b=20

  

if [ $a == $b ]

then

    #If they are equal then print this

    echo "a is equal to b"

else

    #else print this

    echo "a is not equal to b"


fi

Output
$bash -f main.sh

a is equal to b

Practical 14
The while loop enables you to execute a set of commands repeatedly
until some condition occurs. It is usually used when you need to
manipulate the value of a variable repeatedly.
Syntax
while command
do
Statement(s) to be executed if command is true
done
Here the Shell command is evaluated. If the resulting value is true,
given statement(s) are executed. If command is false then no
statement will be executed and the program will jump to the next line
after the done statement.

Example
Here is a simple example that uses the while loop to display the
numbers zero to nine −
#!/bin/sh

a=0

while [ $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done

Upon execution, you will receive the following result −


0
1
2
3
4
5
6
7
8
9
Each time this loop executes, the variable a is checked to see whether
it has a value that is less than 10. If the value of a is less than 10, this
test condition has an exit status of 0. In this case, the current value
of a is displayed and later a is incremented by 1.
Practical 15
The for-in structure is designed to reference a list of values
sequentially. It takes two operands—a variable and a list of values. The
values in the list are assigned one by one to the variable in the for-
in structure. Like the while command, the for-in structure is a loop.
Each time through the loop, the next value in the list is assigned to the
variable. When the end of the list is reached, the loop stops. Like
the while loop, the body of a for-in loop begins with the
keyword do and ends with the keyword done. The cbackup script
makes a backup of each file and places it in a directory
called sourcebak. Notice the use of the * special character to generate
a list of all filenames with a .c extension.
cbackup

for backfile in *.c


do
cp $backfile sourcebak/$backfile
echo $backfile
done

A run of the program follows:


$ cbackup
io.c
lib.c
main.c
$

The for structure without a specified list of values takes as its list of


values the command line arguments. The arguments specified on the
command line when the shell file is invoked become a list of values
referenced by the for command. The variable used in
the for command is set automatically to each argument value in
sequence. The first time through the loop, the variable is set to the
value of the first argument. The second time, it is set to the value of
the second argument.

You might also like