Os Lab Course Book
Os Lab Course Book
F. Y. B. C. A. (Science)
Semester-II
BCA - 127
Operating Systems Laboratory
Work Book
Name:
College Name: _
Academic Year:
Editors:
Compiled By:
Mrs. Veena Gandhi
Abeda Inamdar Senior College, Pune
Reviewed By:
Prof. Arun Gangarde,
New Arts, Commerce and Science College, Ahmednagar
1
Introduction
1) Students are expected to carry this book every time they come to the
lab for computer science practical.
2) Students should prepare oneself beforehand for the Assignment by
reading the relevant material.
3) Instructor will specify which problems to solve in the lab during the
allotted slot and student should complete them and get verified by the
instructor. However student should spend additional hours in Lab and at
home to cover as many problems as possible given in this work book.
4) Students will be assessed for each exercise on a scale from 0 to 5.
2
Not done 0
Incomplete 1
Late Complete 2
Needs improvement 3
Complete 4
Well Done 5
The operating system and software requirements on server side and also client
side areas given below:
1) Server and Client Side - ( Operating System ) Linux(Ubuntu/Red
Hat/Fedora) – any distribution
2) BASH shell for shell scripts
3
Table of Contents
Linux Commands-I
Assignment No. 3 Page No. 35
(Basic Linux shell commands)
Linux Commands-II
Assignment No. 4 Page No. 43
(Redirection and simple filters)
Linux Commands-III
Assignment No. 5 Page No. 57
(File and Networking Security
commands)
Vi Editor Commands
Assignment No. 6 Page No. 69
Shell Programming – I
Assignment No. 7 Page No. 79
(Basics of shell Programming)
Shell Programming – II
Assignment No. 8 Page No. 82
(Conditional Statement)
4
Assignment Completion Sheet
7
Certificate
8
Assignment 1
Aim: To Study about Linux operating system and installation of OS and application
Pre-requisite: Knowledge of basic operation in Linux operating system and partitioning
The student should read following topics before starting exercises.
Introduction
Linux is a popular version of the UNIX Operating System. It is open source as its source code is freely
available. It is free to use. Linux was designed considering UNIX compatibility. Its functionality list is
quite similar to that of UNIX.
System Utility:
System Utility programs are responsible for doing specialized, individual level tasks .
9
Important features of Linux Operating System
• Portable – Portability means software can works on different types of hardware in same way. A
Linux kernel and application program supports their installation on any kind of hardware platform.
• Open Source – Linux source code is freely available and it is community based development
project. Multiple team’s works in collaboration to enhance the capability of Linux operating system
and it is continuously evolving.
• Multi-User – Linux is a multiuser system means multiple users can access system resources like
memory/ ram/ application programs at same time.
• Multiprogramming – Linux is a multiprogramming system means multiple applications can run at
same time.
• Hierarchical File System – Linux provides a standard file structure in which system files/ user files
are arranged.
• Shell – Linux provides a special interpreter program which can be used to execute commands of
the operating system. It can be used to do various types of operations, call application programs etc.
• Security – Linux provides user security using authentication features like password protection/
controlled access to specific files/ encryption of data.
• Live CD/USB: Almost all Linux distributions have Live CD/USB feature by which user can run/try
the OS even without installing it on the system.
• Graphical user interface (X Window System): People think that Linux is a command line OS,
somewhere its true also but not necessarily, Linux have packages which can be installed to make
the whole OS graphics based as Windows.
• Support’s most national or customized keyboards: Linux is used worldwide and hence available in
multiple languages, and supports most of their custom national keyboards.
• Application Support: Linux has its own software repository from where users can download and
install thousands of applications just by issuing a command in Linux Terminal or Shell. Linux can
also run Windows applications if needed.
Linux Distribution:
Linux distributions take the Linux kernel and combine it with other free software to create complete
packages.
Here, are a few popular Linux Distributions (also called Linux Distro) –
10
Debian Debian is a stable and popular non-commercial
Linux distribution. It is widely used as a desktop
Linux Distro and is user-oriented. It strictly acts
within the Linux protocols.
Fedora Another Linux kernel based Distro, Fedora is
supported by the Fedora project, an endeavor by
Red Hat. It is popular among desktop users. Its
versions are known for their short life cycle.
Gentoo It is a source based Distribution which means
that you need to configure the code on your
system before you can install it. It is not for
Linux beginners, but it is sure fun for
experienced users.
LinuxMint It is one of the most popular Desktop
Distributions available out there. It launched in
2006 and is now considered to be the fourth most
used Operating system in the computing world.
OpenSUSE It is an easy to use and a good alternative to MS
Windows. It can be easily set up and can also run
on small computers with obsolete configurations.
Download Ubuntu 16.04 from https://www.ubuntu.com/download, put the CD into the CD-ROM drive,
change the boot sequence so that CD-ROM can boot first.
OR
If you want to install Ubuntu from the USB flash Disk, change the boot sequence according to the USB
mass storage to boot first.
Press Enter to get a language screen and then select the language of your choice.
11
Install Ubuntu 16.04 – Installation language
12
Click continue on the welcome screen.
13
1. Erase disk and install Ubuntu (i.e. it will format the entire drive and install the OS).
Once you clicked on Install Now, the installer will ask you to confirm the auto partitioning. Click on
continue.
14
2. Something else (i.e. you can manually create the partition and install Ubuntu on your selected
partition), use this advanced mode if you are comfortable in partitioning your drives manually. Click on
continue.
Once you clicked, you would get the following page where installer lists available hard disk. In my case I
have one hard disk size of 100GB, to create a partition; click on New Partition Table to create an empty
partition.
Since this is a new hard disk. Pop up will ask you to confirm, click on continue.
Partition scheme will be like below:
/boot – 500MB
/swap – 2048MB
/ – Remaining (99GB)
Select free space and click on the + sign at the bottom to create partitions. Following shows for /boot
partition.
15
Following is for / (root) partition.
Install Ubuntu 16.04 – root partition
16
Install Ubuntu 16.04 – Formatting Partitions
Select your location next screen.
17
Once it’s done, click on continue.
18
Install Ubuntu 16.04 – Restart After the installation
Once your machine is restarted, you will get a login window. Login with username and password that
you created earlier.
19
From a command shell, use the "concatenate" command: cat /proc/meminfo for memory usage information.
You should see a line starting something like Mem: 64655360, etc. This is the total memory Linux thinks
it has available to use.
• free - m
• vmstat
• top
• htop
You can think of Ubuntu Software Center as Google’s Play Store or Apple’s App Store. It showcases all
the software available for your Ubuntu system. You can either search for an application by its name or just
browse through various categories of software. You can also opt for the editor’s pick. Your choice mainly.
Once you have found the application you are looking for, simply click on it. This will open a page inside
Software Center with a description of the application. You can read the description, see its raiting and also
read reviews. You can also write a review if you want.
20
Once you are convinced that you want the application, you can click on the install button to install the
selected application. You’ll have to enter your password in order to install applications in Ubuntu.
21
But there is also a Canonical Partner repository which is not directly controlled by Ubuntu and includes
closed source proprietary software. Enabling this repository gives you access to more software. Installing
Skype in Ubuntu is achieved by this method.
In Unity Dash, look for Software & Updates.
And in here, under Other Software tab, check the options of Canonical Partners.
22
Open the Software Center and click on the Installed tab. It will show you all the installed software.
Alternatively, you can just search for the application by its name.
To remove the application from Ubuntu, simply click on Remove button. Again you will have to provide
your password here.
Once you have downloaded the .deb file, just double click on it to run it. It will open in Ubuntu Software
Center and you can install it in the same way as we saw in section 1.1.
Alternatively, you can use a lightweight program Gdebi to install .deb files in Ubuntu.
Once you have installed the software, you are free to delete the downloaded .deb file.
23
• Make sure that you are downloading the .deb file from the official source. Only rely on the official website
or GitHub pages.
• Make sure that you are downloading the .deb file for correct system type (32 bit or 64 bit). Read our quick
guide to know if your Ubuntu system is 32 bit or 64 bit.
Remove software that was installed using .deb
Removing software that was installed by a .deb file is the same as we saw earlier in section 1.2. Just go to
Ubuntu Software Center, search for the application name and click on remove to uninstall it.
Alternatively, you can use Synaptic Package Manager. Not necessarily but this may happen that the
installed application is not visible in Ubuntu Software Center. Synaptic Package Manager is lists all the
software that are available for your system and all the software that are already installed on your system.
This is a very powerful and very useful tool.
This is a very powerful and very useful tool. Before Ubuntu Software Center came into existence to provide
a more user-friendly approach to software installation, Synaptic was the default program for installing and
uninstalling software in Ubuntu.
You can install Synaptic package manager by clicking on the link below (it will open Ubuntu Software
Center).
Open Synaptic Manager and then search for the software you want to uninstall. Installed softwares are
marked with a green button. Click on it and select “mark for removal”. Once you do that, click on “apply”
to remove the selected software.
24
This is actually the command line equivalent of what we saw in section 1. Basically, instead of using the
graphical interface of Ubuntu Software Center, you are using the command line interface. Nothing else
changes.
Using the apt-get command to install software is extremely easy. All you need to do is to use a command
like:
# -> sudo apt-get install package_name
Here sudo gives ‘admin’ or ‘root’ (in Linux term) privileges. You can replace package_name with the
desired software name.
apt-get commands have auto-completion so if you type a few letters and hit tab, it will provide all the
programs matching with those letters.
Remove software in Ubuntu using apt commands [recommended]
You can easily remove softwares that were installed using Ubuntu Software Center, apt command or .deb
file using the command line.
All you have to do is to use the following command, just replace the package_name with the software name
you want to delete.
# -> sudo apt-get remove package_name
Here again, you can benefit from auto completion by pressing the tab key.
Using apt-get commands is not rocket science. This is in fact very convenient. With these simple
commands, you get acquainted with the command line part of Ubuntu Linux and it does help in long run.
I recommend reading my detailed guide on using apt-get commands to learn in detail about it.
Install GCC
The following linux command will install gcc compiler on on Ubuntu 18.04 Bionic Beaver. Open up
terminal and enter:
$ sudo apt install g++
Install build-essential
install g++ compiler
Another way to build-essential is to install it as part of build-essential package.
Additionally the package will also install additional libraries as well
as gcc compiler. In most cases or if unsure this is exactly what you need:
$ sudo apt install build-essential
Check G++ version
Confirm your installation by checking for GCC version:
$ g++ --version
g++ (Ubuntu 7.2.0-18ubuntu2) 7.2.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Same For GCC
SET A
1) How can you find out how much memory Linux is using?
2) How do you switch from one desktop environment to another, such as switching from KDE
to Gnome?
3) How do you execute more than one command or program from a single command line entry?
SET B
25
1) How can you install multiple packages using single command?
2) How to remove software that was installed using .deb?
3) Install all Python package.
SET C
1) Install the following Software using sudo apt install :
Before this use sudo apt update
a) python3-pip
b) gcc
c) default-jdk
d) libapache2-mod-php
e) Apache2
f) mysql-server
Assignment Evaluation
26
Assignment 2
Note: The student should read following topics before starting exercises.
2. MATE on Ubuntu MATE Intuitive and robust experience, Simple Interface might seem old
and lightweight, (because it’s intended to be)
Highly customizable
3. GNOME Modern and touch-friendly UI Can extend Resource heavy,
functionalities through GNOME Shell Extension management is
Extensions , not satisfactory
Customizable
4. Cinnamon on Linux Mint Sleek and polished look, Familiar Small icons are not touch
interface, Pretty customizable friendly
27
5. Budgie Solid and intuitive Modern UI, elegant Available only on few
looks, Seamless desktop experience distributions (can be
installed on your own
manually)
6. LXDE on Fedora Extremely fast performing and User interface may
lightweight, Supports almost every Linux seem unappealing
distro
7. Unity Intuitive, New technologies like HUD, Poor implementation of
Customizable by third-party applications notifications,
Very little default tools for
customization,
Inconsistent UI
Desktop Components:
Instructor Notes: Highlight the fact that unlike other operating systems, Ubuntu comes with a completely
clean desktop, by default. Users are free to add icons and files on the desktop according to their
preferences.
GNOME is the default desktop environment for Ubuntu. GNOME (GNU Network Object Model
Environment) is an international effort to build a complete desktop environment—the graphical user
interface, which sits on top of a computer operating system—entirely from free software. This goal
includes creating software development frameworks, selecting application software for the desktop and
working on the programmes.
Which manage application launching, file handling and window and task management. Community
members worldwide contribute to the translation and accessibility of the desktop in multiple languages.
Key Desktop Components on Ubuntu when you start your computer, the first screen displayed on
Ubuntu is the logon screen, where you type your user name and password. The next screen displayed
is the Ubuntu desktop. Ubuntu comes with a completely clean desktop background, free of icons by
default.
Let’s discuss various components like window manager, Panels, Menu, System Tray, Icons, Widgets,
Launcher, dashboards, file manager, display manger, terminal emulator, text editor, configuration tools
etc.
1) Window manager:
Figure 1
An X window manager is a window manager which runs on top of the X Window System, a
windowing system mainly used on Unix-like systems. Unlike the classic Mac OS, macOS (Apple
Macintosh) and Microsoft Windows platforms (excepting Microsoft Windows explorer.exe shell
replacements) which have historically provided a vendor-controlled, fixed set of ways to control how
28
windows and panes display on a screen, and how the user may interact with them, window management
for the X Window System was deliberately kept separate from the software providing the graphical
display. The user can choose between various third-party window managers, which differ from one
another in several ways, including:
29
3. On the Appearance screen, click the “Behavior” tab.
4) System Tray:
System Places menu, you will find the system tray. The system tray holds buttons for commonly used
applications. On Ubuntu these include icons for the Konqueror Web Browser, Amarok media player,
Kopete Instant Messenger, and KContact contact address book.
5) Icons: While Ubuntu comes with a number of icon packs you can select from, online a small number is
installed by default. The first place to look for more icons is on the default repositories.
6) Widgets:
Screen less is a framework that allows adding widgets to your desktop. The Screen less PPA provides
numerous screen less (desktop widgets), such as RSS readers, weather, clock, countdown, a Conky-
like system information widget, folder view, calendars, sensors, and much more.
7) Launcher: Unity Launchers are actually files stored in your computer, with a '.desktop' extension. In
earlier Ubuntu versions, these files were simply used so as to launch a specific application, but in Unity
they are also used so as to create right-click menus for each application, which you can access from the
Unity Launcher. How do I get desktop launcher on Ubuntu?
1. Right-click unused space in any panel (the toolbars at the top and/or bottom of the screen)
2. Choose Add To Panel...
3. Choose Custom Application Launcher.
4. Fill in Name, Command, and Comment. ...
5. Click the No Icon button to select an icon for your launcher. ...
6. Click OK.
7. Your launcher should now appear on the panel.
8) Terminal Emulator: Guake, ROXTerm, XTerm, Eterm, Gnome Terminal are number of terminal
emulators.
• Sakura. Sakura is a terminal emulator based just on GTK and VTE.
• LilyTerm. LilyTerm is a terminal emulator based off of libvte that aims to be fast and lightweight, Licensed
under GPLv3.
• Konsole. If you're a KDE or Plasma user, you must know Konsole.
Customizing the Desktop Ubuntu and its derivatives can be customized through a Graphical User Interface
or a Command Line Interface. The graphical tools to customize the desktop are available as menu options
in the System menu. Point to Preference s on the System menu to view the tools.
Changing the Background: The desktop background is the image or color applied to your desktop.
30
Screen Description
Figure 2: Launching Appearance Preferences Dialogue Box
On the System menu, point to Preferences and then click Appearance. The
Appearance Preferences dialogue box opens.
Nice to Know: You can also right-click the desktop and select Change
Desktop Background to open the Appearance Preferences dialogue box.
Figure 3: Changing the Desktop Wallpaper
31
Click the Background tab and select the wallpaper No Wallpaper.
You can only view colors if you have not set any desktop
wallpaper.
The desktop theme controls the visual appearance of the buttons, scroll
bars, icons, panels, borders etc. A number of themes are provided with
Ubuntu.
32
Figure 15: Saving a Modified Theme
Provide a name for the theme in the Name
box and a description,
if you want, in the Description box. Click Save.
33
Figure 26: Customising Screen Resolution
Click Apply. The Keep Resolution dialogue box opens, prompting
you to confirm settings or use the previous resolution and revert to
the original settings. Click Keep resolution to apply new changes.
Exercises:
Set A:
Set B:
1) Change your desktop Background and wallpaper.
2) Select color box and Select the desktop color of your choice and apply color to your
background.
3) On the System menu, point to Preferences and click Screensaver. The Screensaver Preferences dialogue
box opens. Select screensaver list and apply any one you like for your system.
4) Customize your window borders and icons.
5) Specifying Theme Name and Description for your system and View an Application in a Modified
Theme
Set C:
1. Launch a Screen Resolution Preferences Dialogue Box and change default resolution by using
Customize Screen Resolution.
2. Change the time and date of your system.
Assignment Evaluation
34
Assignment -3
35
Command Meaning Example
36
make typescript or record all the E.g.
terminal activities. After executing $ script information.txt
the script command it starts recording The output will contain content of
everything printed on the screen Information.txt file,created by script
including the inputs and outputs until command.
exit. -c
command
This option is used when we want to
run a particular command.
$ script –c cal calender.txt
-e
–return
This option simply return exit code of
the child process.
-f
–flush
This option is used to run flush output
after each write.
tput Using tput you can control the color • Set the Cursor Position using
and cursor of your terminal. tput cup.
E.g.$ tput cup 2 3
• Clear the Screen Using tput
clear
E.g.$tput clear
• Get the Number of Columns
and Lines of a Terminal
E.g. $ tput cols
$tput lines
• Change the Terminal
Background Color using
tputsetb
E.g. $tputsetb 4
• Change the Foreground Color
using tputsetf
E.g. $tputsetf 4
37
General Purpose Commands
Environment variables are dynamic values which affect the processes or programs on a computer. They
exist in every operating system, but types may vary. Environment variables can be created, edited, saved,
and deleted and give information about the system behavior.
38
cd This command is used to change directory. $ cd /
rmdir $ rmdir
This command will remove/delete an existing FYBCA
directory, provided it is empty.
cat Cat command reads data from the 1) To read a single file.
file and gives their content as $ cat filename
output. It helps us to create, view, 2) To view multiple files
concatenate files. $ cat filename1 filename2
3) To view contents of a file
preceding with line numbers
$ cat-n filename
4) Cat command can append the
contents of one file to the end of
another file.
$ cat file1 >>file2
5) Cat command can display content
in reverse order using tac
command.
$ tac filename
39
ls ls is a Linux shell command that 1) List files with ls with no option.
lists directory contents of files and $ ls
directories. 2) Open Last Edited File
$ls -t
3) Display All Information About
Files/Directories
$ls –l
4) isplay File Size in Human
Readable Format
$ls –lh
5) Order Files Based on Last
Modified Time
$ls –lt
6) Display Hidden Files
$ls -a
40
diff diff stands for difference. This diff [option] file1 file2
command is used to display the
differences in the files by
comparing the files line by line.
cmp cmp command in Linux/UNIX is $cmp [OPTION]... FILE1 [FILE2 [SKIP1
used to compare the two files byte [SKIP2]]]
by byte and helps you to find out
whether the two files are identical
or not.
comm comm compare two sorted files line $comm[option]….file1 file2
by line and write to standard output
the lines that are common and the
lines that are unique.
tar The Linux ‘tar’ stands for tape $ tar [options] [archive file]
archive, is used to create Archive [file or directory to be archived]
and extract the Archive files.
zip zip is used to compress the files to zip [option] zipfilefiles_list
reduce file size and also used as file E.g. $ myfile.zip filename.txt
package utility.
unzip unzip will list, test, or extract files unzip myfile.zip
from a ZIP archive
passwd passwd command in Linux is used $ passwd
to change the user account
passwords.
patch Patch is a command that is used to patch [options] [original filename]
apply patch files to the files like [patchfile]]
source code, configuration. Patch
files holds the difference between
original file and new file.
Exercises:
Set A:
41
Set B:
1. Create a directory named FYBCA under that create a 3 directories CO, RDBMS and O.S. Create
files under subdirectories CO and RDBMS and move these files to O.S.
2. Display username, user id, hostname, kernel name along with system information.
4. Display list of all files ending with .txt from current working directory.
5. Copy the file MyFile.txt to directory assignment1 and rename it to t_1.txt.
6. Display last modification and access time of particular file.
7. Create file student.txt and display size of file in bytes.
8. Display first and last 5 lines of student.txt
9. Prepare two text files and check output of diff, comm and cmp commands.
Set C:
1. Make a list of all filenames in /etc that contain the string samba.
2. Make a sorted list of all files in /etc that contain the case insensitive string samba.
3. Write a line that receives cities.txt file and sort that file.
4. Accept text file and display second to the seventh character of that file.
5. Create a text file which contains name of cities include city name pune in that file Display Pune
along with previous and next city name.
6. Put a sorted list of all logged on users in onlineusers.txt.
7. Accept the file and display that file along with line numbers.
Assignment Evaluation
42
Assignment 4
With redirection, the above standard input/output can be changed. The default files where a command
reads its input, sends its output and error messages are called standard input(stdin), standard output(stdout)
and standard error(stderr) respectively.
By default all the above three files are attached with the terminal on which the command is executing.
Therefore, every command, by default, takes its input from the keyboard and sends its output and error
messages to the display screen. Redirection is used to detach default file from the command and attach
some specific file.
Pipes allow you to send output of one command as input to the other command. The commands that are
connected via a pipe are called filters.
In addition to redirecting input/output to a named file, you can connect two commands together so that the
output from one program becomes the input of the next program. Two or more commands connected in
this way form a pipe. To make a pipe, put a vertical bar (|) on the command line between two commands.
When a pipe is set up between two commands, the standard output of the command to the left of the pipe
symbol becomes the standard input of the command to the right of the pipe symbol.
Command Symbol Description Format & Example
Input Redirection < Redirection It detaches $cat < abc.txt
the keyboard from the Takes its input from
standard input of abc.txt and the output
command and attaches by default is
specific file on console. The
effect is same as $cat
tempfile
Output Redirection > It detaches the console $cat > file1
from Takes its input from
the standard output of keyboard by default
command and attaches and writes the output
specific file to file1, effectively
whatever typed
at the keyboard goes
into tempfile
$cat file1 abc.txt >
43
file2
The contents of file1
and abc.txt will be
concatenated and
send to file2
$cat file1 > /dev/lp0
The contents of file
file1 will be sent to
printer instead of
console
Output Redirection >> In output redirection the $cat file1 > file1
without overwriting file is cleared before The file1 contents
writing to it. will be cleared
The >> is used so that $cat file2 >> file2
output is appended and The file2 will have
not overwritten its contents appended
to it
Pipe | The pipe character | is $ ls –l | grep “abc”
used Displays the line in
between two commands the output of ls –l
so containing pattern abc
that output of first
command
is send as input to the
second
command
Filters in Linux
When a program takes its input from another program, performs some operation on that input, and writes
the result to the standard output (which may be piped to yet another program), it is referred to as a filter.
Linux has a number of filters.
• grep: Find lines in stdin that match a pattern and print them to stdout.
• sort: Sort the lines in stdin, and print the result to stdout.
• uniq: Read from stdin and print unique (that are different from the adjacent line) to stdout.
• cat: Read lines from stdin (and more files), and concatenate them to stdout.
• more: Read lines from stdin, and provide a paginated view to stdout.
• cut: Cut specified byte, character or field from each line of stdin and print to stdout.
• paste: Read lines from stdin (and more files), and paste them together line-by-line to stdout.
• head: Read the first few lines from stdin (and more files) and print them to stdout.
• tail: Read the last few lines from stdin (and more files) and print them to stdout.
• wc: Read from stdin, and print the number of newlines, words, and bytes to stdout.
• tr: Translate or delete characters read from stdin and print to stdout.
44
In previous assignment, cat ,head, tail, more , pg, tr etc are covered.
Some of the most commonly used filters are explained below:
• wc
• sort
• unique
• grep
• cut
• paste
wc command
wc stands for word count. As the name implies, it is mainly used for counting purpose.
It is used to find out number of lines, word count, byte and characters count in the files specified in the file
arguments .By default it displays four-columnar output.First column shows number of lines present in a
file specified, second column shows number of words present in the file, third column shows number of
characters present in file and fourth column itself is the file name which are given as argument
Syntax:
wc [OPTION]... [FILE]...
Options :
1. -l: This option prints the number of lines present in a file. With this option wc command displays two-
columnar output, 1st column shows number of lines present in a file and 2nd itself represent the file name.
2. -w: This option prints the number of words present in a file. With this option wc command displays
two-columnar output, 1st column shows number of words present in a file and 2nd is the file name.
3. -c: This option displays count of bytes present in a file. With this option it display two-columnar output,
1st column shows number of bytes present in a file and 2nd is the file name.
4. -L: The ‘wc’ command allow an argument -L, it can be used to print out the length of longest (number
of characters) line in a file.
$ cat state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
$ wc state.txt
5 7 63 state.txt
$ wc -l state.txt
5 state.txt
$ wc -w state.txt
7 state.txt
$ wc -c state.txt
63 state.txt
45
$ wc -L state.txt
17 state.txt
SORT command
SORT command is used to sort a file, arranging the records in a particular order. By default, the sort
command sorts file assuming the contents are ASCII. Using options in sort command, it can also be used
to sort numerically.
Syntax :
sort [options] [files]
Sort Options:
Some of the options supported are:
sort -b: Ignore blanks at the start of the line.
sort -r: Reverse the sorting order.
sort -o: Specify the output file.
sort -n: Use the numerical value to sort.
sort -M: Sort as per the calendar month specified.
sort -u: Suppress lines that repeat an earlier key.
sort -k POS1, POS2: Specify a key to do the sorting. POS1 and POS2 are optional parameters and are
used to indicate the starting field and the ending field indices. Without POS2, only the field specified by
POS1 is used. Each POS is specified as “F.C” where F represents the field index, and C represents the
character index from the start of the field.
sort -t SEP: Use the provided separator to identify the fields.
Examples
Assume the below initial contents of file1.txt for the following examples
01 Priya
04 Shreya
03 Tuhina
02 Tushar
46
In this example, the sorting is done similar to the above example, but the result is in the reverse order.
Uniq Command
The uniq command in Linux is a command line utility that reports or filters out the repeated lines in a file.
In simple words, uniq is the tool that helps to detect the adjacent duplicate lines and also deletes the
duplicate lines. uniq filters out the adjacent matching lines from the input file(that is required as an
argument) and writes the filtered data to the output file .
47
s : Avoid comparing first N characters.
u : Prints only unique lines.
w : Compare no more than N characters in lines
$ uniq -D example.txt
unix operating system
unix operating system
48
unix dedicated server
In the above example the uniq command, just compares the last fields. For the first two lines, the last
field contains the string "system". Uniq prints the first line and skips the second. Similarly it prints the
third line and skips the fourth line.
grep command
The grep filter searches a file for a particular pattern of characters, and displays all lines that contain that
pattern. The pattern that is searched in the file is referred to as the regular expression (grep stands for
globally search for regular expression and print out).
Syntax:
grep [options] pattern [files]
Options Description
-c : This prints only a count of the lines that match a pattern
-h : Display the matched lines, but do not display the filenames.
-i : Ignores, case for matching
-l : Displays list of a filenames only.
-n : Display the matched lines and their line numbers.
-v : This prints out all the lines that do not matches the pattern
-e exp : Specifies expression with this option. Can use multiple times.
-f file : Takes patterns from file, one per line.
-E : Treats pattern as an extended regular expression (ERE)
-w : Match whole word
-o : Print only the matched parts of a matching line,with each such part on a separate output line.
Sample Commands
1. Case insensitive search : The -i option enables to search for a string case insensitively in the give file.
It matches the words like “UNIX”, “Unix”, “unix”.
49
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.
2. Displaying the count of number of matches : We can find the number of lines that matches the given
string/pattern
$grep -c "unix" geekfile.txt
Output:
2
3. Display the file names that matches the pattern : We can just display the files that contains the given
string/pattern.
$grep -l "unix" *
or
$grep -l "unix" f1.txt f2.txt f3.xt f4.txt
Output:
geekfile.txt
4. Checking for the whole words in a file : By default, grep matches the given string/pattern even if it
found as a substring in a file. The -w option to grep makes it match only the whole words.
$ grep -w "unix" geekfile.txt
Output:
unix is great os. unix is opensource. unix is free os.
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.
5. Displaying only the matched pattern : By default, grep displays the entire line which has the matched
string. We can make the grep to display only the matched string by using the -o option.
6. Show line number while displaying the output using grep -n : To show the line number of file with the
line matched.
$ grep -n "unix" geekfile.txt
Output:
1:unix is great os. unix is opensource. unix is free os.
4:uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.
7. Inverting the pattern match : You can display the lines that are not matched with the specified search
sting pattern using the -v option.
50
Unix linux which one you choose.
8. Matching the lines that start with a string : The ^ regular expression pattern specifies the start of a line.
This can be used in grep to match the lines which start with the given string or pattern.
9. Matching the lines that end with a string : The $ regular expression pattern specifies the end of a line.
This can be used in grep to match the lines which end with the given string or pattern.
$ grep "os$" geekfile.txt
$cat pattern.txt
Agarwal
Aggarwal
Agrawal
Syntax:
cut OPTION... [FILE]...
When using the cut command you must use one and only one of the following options:
• -f (--fields=LIST) - Select by specifying a field, a set of fields, or a range of fields. This is the
most commonly used option.
• -b (--bytes=LIST) - Select by specifying a byte, a set of bytes, or a range of bytes.
• -c (--characters=LIST) - Select by specifying a character, a set of characters, or a range of
characters.
• Other options are:
• -d (--delimiter) - Specify a delimiter that will be used instead of the default “TAB” delimiter.
• --complement - complement the selection. When using this option cut will display all bytes,
characters or fields except the selected
Let us consider two files having name state.txt and capital.txt contains 5 names of the Indian states and
51
capitals respectively.
$ cat state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Without any option specified it displays error.
$ cut state.txt
cut: you must specify a list of bytes, characters, or fields
Try 'cut --help' for more information..
$ cut -f 1 state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Command prints field from first to fourth of each line from the file.
Command:
$ cut -d " " -f 1-4 state.txt
Output:
52
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Paste Command
Paste command is one of the useful commands in Unix or Linux operating system. It is used to join files
horizontally (parallel merging) by outputting lines consisting of lines from each file specified, separated
by tab as delimiter, to the standard output. When no file is specified, or put dash (“-“) instead of file
name, paste reads from standard input and gives output as it is until a interrupt command [Ctrl-c] is
given.
Syntax:
paste [OPTION]... [FILES]...
The options of paste command are:
• -d : Specify of a list of delimiters.
• -s : Paste one file at a time instead of in parallel.
• --version : version information
• --help : Help about the paste command.
Let us consider three files having name state, capital and number. state and capital file contains 5 names
of the Indian states and capitals respectively. number file contains 5 numbers.
$ cat state
Arunachal Pradesh
Assam
Andhra Pradesh
Bihar
Chhattisgrah
$ cat capital
Itanagar
Dispur
Hyderabad
Patna
Raipur
Without any option paste merges the files in parallel. The paste command writes corresponding lines
from the files with tab as a deliminator on the terminal.
53
2 Assam Dispur
3 Andhra Pradesh Hyderabad
4 Bihar Patna
5 Chhattisgrah Raipur
In the above command three files are merges by paste command.
First and second file is separated by '|' and second and third is separated by ','.
After that list is exhausted and reused.
2. -s (serial): We can merge the files in sequentially manner using the -s option. It reads all the lines from
a single file and merges all these lines into a single line with each line separated by tab. And these single
lines are separated by newline.
In the above command, first it reads data from number file and merge them into single line with each line
separated by tab. After that newline character is introduced and reading from next file i.e. state starts and
process repeats again till all files are read.
Combination of -d and -s: The following example shows how to specify a delimiter for sequential
merging of files:
54
Exercises:
Set A
1. Create any text file and count number of bytes, words, lines and length of longest line in file.
2. Count number of files in current working directory.
3. Redirect output of long listing of directories in abc.txt
4. Count number of users who are logged in and store output in a.txt
5. Displays a list of directories and how much space they consume, sorted from the largest to the smallest.
6. Concatenate two files a.txt , b.txt into third file c.txt
Set B
1. Create the following text file a.txt and write commands based on it.
Unix distributed 05 server
Linux virtual 3 server
Unix distributed 05 server
Distributed processing 6 system
a) Sort the above file in alphabetical order.
b) Sort the above file in descending order.
c) Sort the above file in numerical order.
d) Sort the above file on second field.
e) Sort the above file on second and fourth filed on reverse order.
f) Remove duplicate entries from above file and store in c.txt
2. Create the following text file a.txt and write commands based on it
welcome to ostechnix
welcome to ostechnix
Linus is the creator of Linux.
Linux is secure by default
Linus is the creator of Linux.
Top 500 super computers are powered by Linux
a) Write a linux command to remove consecutive duplicate lines.
b) Write a linux command to display only uniq lines.
c) Write a linux command to display only duplicate lines
d) Write a linux command to display number of occurrences of each line in a file.
e) Write a linux command to display limit the comparison to first 4 characters of lines in a file and
display the repeated lines.
f) Write a linux command to avoid the comparison with the first 4 characters of lines in a file.
3. Create the following text file a.txt and write commands based on it
This is line 1 UNIX UNIX
This is line 2 unix
This is line 3 Unix Unix
This is line 4 hello
a) Write a linux command to display lines that search pattern “unix” .
b) Write a linux command to display lines that search pattern “unix” in case-insensitive manner .
c) Write a linux command to display line numbers that search pattern “unix”
d) Write a linux command to display count of lines that search pattern “unix”
e) Write a linux command to display lines that does contain pattern “unix”
f) Write a linux command to display lines that contains starting letter U and ending with letter x.
55
Set C
1. Create file as follows and write commands for same.
$ cat file.txt
unix or linux os
is unix good os
is linux good os
a) Write a linux command to print characters of 4th position.
b) Write a linux command to print characters by range 4-7.
c) Write a linux command that prints the second field in each line by treating the space as delimiter.
2. Create file as follows and write commands for same.
Linux
Unix
Solaris
HPUX
AIX
a) Write a linux command to join all lines separated by tab.
b) Write a linux command to join all lines separated by comma.
c) Write a linux command to merge a file by pasting the data into 2 columns
d) Write a linux command to merge a file by pasting the data into 2 columns using a colon separator
Assignment Evaluation
56
Assignment 5
Linux is a multi-user operating system. In Multi user environment more than one user can access
one operating system. So practically there is requirement to protect the users from each other.
Linux provides different types of commands to prevent access from unauthorized user. These
commands are related to set permissions for file.
In Linux operating system, each file and directory has3 types of owner:
➢ User:A user is the owner of the file. By default, the person who created a file becomes its
owner. Hence, a user is also sometimes called an owner.
➢ Group: A user- group can contain multiple users. All users belonging to a group will have
the same access permissions to the file. Suppose you have a project where a number of
people require access to a file. Instead of manually assigning permissions to each user, you
could add all users to a group, and assign group permission to file such that only this group
members and no one else can read or modify the files.
➢ Other:Any other user who has access to a file. This person has neither created the file, nor
belongs to a user or group who could own the file. Practically, it means everybody else.
Hence, when you set the permission for others, it is also referred as set permissions for the
world.
Every file and directory in your Linux system has following 3 types permissions defined
for all the 3 owners discussed above:
➢ Read (r): This permission give you the authority to open and read a file. Read permission
on a directory gives you the ability to lists it’s content.
➢ Write (w): The write permission gives you the authority to modify the contents of a file.
The write permission on a directory gives you the authority to add, remove and rename files
stored in the directory.
➢ Execute (x):In Linux, you cannot run a program unless the execute permission is set. If the
execute permission is not set, you might still be able to see/modify the program
code(provided read & write permissions are set), but cannot run program.
57
We will see how the first portion of ls command is interpreted. It consists of a character indicating
the file type, followed by three sets of three characters that conveythe reading, writing and execution
permission for the owner, group, and other.
1. chmod :chmodstands for 'change mode'. Using the command, we can set permissions (read,
write, execute) on a file/directory for the owner, group and other.
Syntax:
chmod permissions filename
There are 2 ways to use this command.
a. Absolute(Numeric) mode
In this file permissions are not represented using 3 digit octal number.
58
Here are examples of chmod using Absolute mode.
NOTE:
Becoming a Super user for a short while
It is often necessary to become the superuser to perform important system
administration tasks, but as you have been warned, you should not stay logged in as
the superuser. There is a program that can give you temporary access to the superuser's
privileges. This program is called su (short for substitute user) and can be used in
those cases when you need to be the superuser for a small number of tasks. To become
the superuser, simply type the su command. You need to typesuperuser's password.
After executing the su command, you have a new shell session as the superuser. To
exit the superuser session, type exit and you will return to your previous session.
[me@linuxbox me]$ su
Password:
b. Symbolic mode
[root@linuxbox me]#
In the Absolute mode, you change permissions for all 3 owners. In the symbolic mode, you can modify
permissions of a specific owner. It makes use of mathematical symbols to modify the file permissions.
Operator Description
+ ds a permission to a file or directory
- moves the permission
= ts the permission and overrides the permissions set earlier.
59
The various owners are represented as -
u User/Owner
g Group
o Other
a all
➢ chmodo+r first.txt
Beforechmod
[root@linuxbox me]$ls -l
-rwx - - x- -x 1 root root 16 NOV 6 10:19 first.txt
After chmod
[root@linuxbox me]$ ls -l
-rwx r—x r—x 1 root root 16 NOV 6 10:19 first.txt
2. chown :chown means change owner. You can change the owner of a file by using the
chown command.In order to change the owner of a file, you must be the superuser. To do this
use su command, then we executed chown, and finally we typed exit to return to our previous
session.
Example:
[me@linuxbox me]$ su
Password:
[root@linuxbox me]# chown fybca12 first.txt
[root@linuxbox me]# exit
[me@linuxbox me]$
Beforechown
[root@linuxbox me]$ ls -l
-rwx - - x- -x 1 rootroot 16 NOV 6 10:19 first.txt
Afterchown
[root@linuxbox me]$ ls -l
-rwx - - x- -x 1 fybca12 root 16 NOV 6 10:19 first.txt
3. chgrp :The group ownership of a file or directory may be changed with chgrp.
60
Example:
[me@linuxbox me]$ su
Password:
[root@linuxbox me]# chgrp fybca12 first.txt
[root@linuxbox me]# exit
[me@linuxbox me]$
Before chgrp
[root@linuxbox me]$ ls -l
-rwx - - x- -x 1 fybca12root 16 NOV 6 10:19 first.txt
Afterchgrp
[root@linuxbox me]$ ls -l
-rwx - - x- -x 1 fybca12 fybca12 16 NOV 6 10:19 first.txt
What is a Process?
An instance of a program is called a Process. In simple terms, any command that you give to your
Linux machine starts a new process.
Types of Processes:
1. Foreground Processes: They run on the screen and need input from the user.
E.g. Office Programs
2. Background Processes: They run in the background and usually do not need user input. E.g.
Antivirus program.
Following are the Linux commands for Process Management:
Command Usage Example
61
fg It is used to continue a program which [root@linuxbox me]# fg
was stopped and bring as foreground
process. command moves last process to
foreground.
root@tryit-hip:~# ps 176
PID TTY STAT
TIMECOMMAND
176 ? Ss 0:00
bash
➢ top: This utility tells the user about all the running processes on the Linux machine.
62
Press 'q' on the keyboard to move out of the process display.
➢ at :The at command schedules a command to be run once at a particular time. For scheduling a
job using at command use shell script file. Specify commands in script file and run at particular
time.
63
Example:
vi Hello.sh
echo “Hello”
Save Hello.sh
You can check schedule status of Hello.sh file using atq Command
[root@linuxbox me]# atq
12 2019-05-10 11:20 root
64
cd “dirname” – To change the
directory
quit – logout
65
uuenode It is used to encode oot@localhost]#uuencodefirst.txt
contents of file. So that encode.txt
contents are secured.
rst.txt is a plain text file
encoded to encode.txt
uudecode It is used to decode root@localhost]#uudecodeencode.txt
contents of file. try.txt
These commands are used to manage local accounts or users like creating new user, modifying or
deleting user account.
[root@localhost]#useradd
fybca12 –d /home/fybca12
[root@localhost]#useraddfybca12
-s /bin/csh
root@localhost]#usermod -p
$1$d8 fybca12
66
userdel delete a user account [root@localhost]#userdel –r
and user’s related files fybca12
Exercise
SET A
Perform the commands on the system and write the commands.
1. Create three text files one.txt, two.txt, three.txt. Check the permissions of created files.
2. Change permission of one.txt as give read, write, execute access for owner, Read, write for
group and only read for other.
3. Change permission of two.txt as read, write, and execute access for owner, group and other.
4. Change permission of three.txt as read, write access for owner, Read, Execute for group and
only Execute for other.
5. Create directory ‘Assignment’. Create two subdirectories ‘Ass1’, ‘Ass2’ under it. Check the
permission of directory.
6. Change permission of ‘Assignment’ directory. Give read, read, write, and execute access for
owner, group and other including subdirectories also.
7. Change the owner of one.txt to (username)
8. Change the group of two.txt to (username)
SET B
1. Check the processes that are running on the system. Write the details of at least 3 process below.
2. See the details of particular process by specifying Process ID. Write command and details of
particular process.
3. Terminate process.
4. Check the free and used memory status of system in MB and GB.
5. Change the priority of process to -5.
6. Execute top command and see the output.
67
7. Create trial.txt file. Type 3 echo statements, date, ls command in that file. Schedule the execution
status of that file at 15:30 (ie 3.30pm)
8. Check the schedule status of trial.txt
SET C
1. Check the IP address of your system. Mention the command with IP address.
2. Check the system with IP address is running in LAN.
3. Write a command to domain name of IP address _ connected in
LAN. Write domain name also.
4. Use ftp to upload one.txt to remote server.
5. Download file from remote server using ftp.
Assignment Evaluation
68
Assignment 6
Aim: By learning to use Vi editor can benefit user in creating scripts and editing files.
Prerequisites: Basic knowledge of Linux operating System.
What is Vi :
The Default editor that comes with the UNIX operating system is called Vi (Visual) Editor
Using the Vi Text Editor:
➢ To Start vi
To edit a file with vi, type any of the following commands at the UNIX system prompt.
2 vi filename Creates a new file if it already does not exist, otherwise opens an existing
file.
3 vi -r filename It recovers file from system crash (this may not recover all of the
changes you made to your file in your last editing session)
➢ To Exit from Vi
You can save and quit Vi editor from command mode. Before writing save or quit command you have to
press colon (:). Colon allows you to give instructions to Vi.
2 :wq Save the file(write) and quit (i.e. save and quit)
69
3 :w Save the file but keep it open
To exit from Vi, first ensure that you are in command mode. Now, type:wq and press enter. It will save
and quit Vi.
Vi modes:
i) Command mode: While in command mode, everything you type is executed as a command to edit your
document. This mode enables you to perform administrative tasks such as saving the files, executing the
commands, moving the cursor, cutting (yanking) and pasting the lines or words, as well as finding and
replacing. In this mode, whatever you type is interpreted as a command.
ii) Input mode: This mode enables you to insert text into the file. Everything that's typed in this mode is
interpreted as input and placed in the file. While in input mode, everything you type is inserted into your
document (including command mode commands).
NOTE: Vi always starts in the command mode. To enter text, you must be in the insert mode for which
simply type i. To come out of the insert mode, press the Esc key, which will take you back to the command
mode. Change from input mode to command mode, press the Esc key.
Basic Vi Commands:
There are several ways to change from command mode to input mode that is listed below.
1) Entering input mode: (Editing Files)
70
To edit the file, you need to be in the insert mode. There are many ways to enter the insert mode from the
command mode –
To add text you position the cursor over a character and press an “a”. This puts you in a special
mode of operations called “insert mode”. Now everything typed is appended to the text after the
character the cursor was positioned over:
John Joxxyyzzhn
Jim a Jim
Pat Pat
xxyyzz
Steve Steve
~ ~
~ add xxyyz z ~
~ ~
“names” 4 lines 19 characters INSERT
When you are done adding text, you press the ESC key. When you press ESC key, the cursor
moves back to the last character you entered.
71
Joxxyyzzhn Joxxyyzzone
Jim a twohn
Pat Jim
Steve oneCR Pat
~ twoESC Steve
~ ~
~ ~
~ ~
EmbeddedCR
The appending started between the z and hn of the first line, causing the hn to be carried to the
next line when the CR i.e. () was pressed.
1. Perform the following changes to your file. Specify the command and the resulting text as an
answer.
Action Command typed Result
Change Jim in line 3 to Jirem
Insert a new line “Tom and Jerry”
after line number 3.
Insert a new line at the end
2) Deleting Characters and Words
Here is a list of important commands, which can be used to delete characters, wordsand lines in an open
file −
Sr.No Command Description
1 x Deletes the single character under the cursor location.
2 X Deletes the character before the cursor location
3 Nx Delete N Character,starting with character under cursor
4 dw Deletes from the current cursor location to the next word
5 dNw Deletes N words beginning with character under cursor
6 d^ Deletes from the current cursor position to the beginning of the line
7 d$ Deletes from the current cursor position to the end of the line
8 D Deletes from the cursor position to the end of the current line
9 dd Deletes the current lin.
10 3dd It deletes 3 lines
11 dw Delete word
12 4dw Delete 4 words
1. Create a file in Vi editor. Perform the following operation by specifying the command and the resulting
text asanswer.
Action (from current cursor position) Command typed Result
Delete 2 characters
Delete 3 characters from 3rd line
Delete 1stline
Delete 4thline
72
3) Copy, Paste, Undo and Repeat Commands
You can copy lines or words from one place and then you can paste them at another place using the
following commands –
Sr.No Command Description
1 yy Copies the current line.
2 Nyy Copy the next N lines, including the current line, into the buffer.
2 yw Copy one word
3 p(lowercase) Paste the copied text after the cursor.
4 P(Uppercase) Paste before the current line
5 9yy Yank current line and 9 lines below.
6 U Undo the last command
7 .(dot) Repeat the last command
1. Create a file in Vi editor. Perform the following operation by specifying the command and the resulting
text as answer.
Action (from current cursor Command typed Result
position)
Cutline 2, 3 and put those after two line
Copy line 3 and put it after line 4.
Undo all the changes
Locate the content at line 2
73
5 0(Zero) Move Cursor to start of the current line(the one with the arrow)
6 $ Move Cursor to the end of the current line
7 w Move cursor to beginning of next word
8 b
9 :0<return> or 1G Move cursor to first line in the file
10 :n<return>or nG Move cursor to line ‘n’ in file
11 :$<return> or G Move cursor to last line in file
12 nj, move more than one column or line at a time
nk,
nh,
nl
1. Create a file in Vi editor. Perform the following operation by specifying the command and the resulting
text asanswer.
6) Searching a String:
In command mode, with the help of '/’, string can be searched in forward direction and with the help of ? ,
string can be searched in backward direction. For example, /abc will do a forward search for string abc
whereas? abc will do a backward search for string abc.
1. Create a fileMy_college in Vi editor. Perform the following operation by specifying the command and
the resulting text asanswer.
74
Action (from current cursor position) Command typed Result
Search for keyword “College”
Search keyword “College” in forward
direction
7) ReplacingText:
The substitution command (:s/) enables you to quickly replace words or groups of words within your files.
Following is the syntax to replace text –
Syntax is - :s/old_string/new-string/g
The g stands for globally. The result of this command is that all occurrences on the cursor's line are
changed.
For example:
1) :s/java/os
Here “java” represents old string and “os” represents new string. It replaces each “java” string in a line
with “os”string.
2) :s/geeksforgeeks/gfg/
Input Screen:
75
Output Screen
3) :%s/pattern/replace/
It replaces every occurrence of a string in the entire text.
For example -- :%s/gfg/geeksforgeeks/
4) :1,$ s/old_string/new string/
It replaces the old string start from first line by new string to the last line.
For Example -
: 1, $ s/readable/changed/
Input Screen:
76
Output Screen:
8) Control Commands (Scrolling Commands) : There are following useful commands which can used
along with Control Key:
Exercise:
Set A:
1. Create a file by name Mycollege.txt with at least 25 lines long using vi editor’s input
commands -“a” and “i”.Also try there place mode by examining the toggle feature of “i”
character.
2. Create a file by name with least25lineslongusingvieditor’sinputcommands–“a” and
“i”.Also try search command on the file.
Set B
1CreateafilebyInput devices.txt with least25lineslongusingvieditor’sinputcommands and try the
following using Vi commands
a) Move to the first line of the file.
b) Insert a blank line below the 3rd line
c) Delete any 3 lines
d) Join any two lines together
e) Restore the single deleted line
f) Search the keyword “dev” from a file.
2. Create a file name containing five lines and execute the following set of commands
77
of vi editor and describe the result on thepaper.
Sr. No Command
1 cc
2 D
3 C
4 s
5 S
6 rchr
7 R
Set C:
1Createafilebyname My_country.txt with least25lineslongusingVieditor’sinputcommands and
try the following using Vi commands
a) Move to the first line of the file
b) Replace each occurrence of word “College” with Institute.
c) Move to the beginning of 2nd line.
d) Apply control command on file.
e) Search a keyword “India” overall in a file.
f) Copy and paste any 4 lines from a file.
Assignment Evaluation
78
Assignment 7
If you are using any major operating system you are indirectly interacting to shell. If you are running
Ubuntu, Linux Mint or any other Linux distribution, you are interacting to shell every time you use
terminal. So let us discuss about linux shells and shell scripting.
A shell in a Linux operating system takes input from you in the form of commands, processes it, and then
gives an output. It is the interface through which a user works on the programs, commands, and scripts. A
shell is accessed by a terminal which runs it.
There are mainly 4 important types of shells that are widely used.
They include:
• Bourne Shell (sh)
• C Shell (csh)
• Korn Shell (ksh)
• Bourne Again Shell (bash)
When you run the terminal, the Shell issues a command prompt (usually $), where you can type your
input, which is then executed when you hit the Enter key. The output or the resultis thereafter displayed
on the terminal.
Different statements used in shell script are,
Statement Usage Example
Expr Write the result of the expression on the standard mult=`expr $x * $y`
output. This command is primarily intended for x=`expr $x + 1`
arithmetic and string manipulation (convert string to
integer.)
79
Set Assign a value to a shell variable (or multiple values set val = 7
to multiple variables). set without arguments set new_val = “like seven”
displays the names and values of all shell variables, echo $new_val
sorted by name
Unset Delete a shell variable. This does not just clear the $a=”unset example”
variable, but makes it “not exist”. echo $a
All variables are removed by "unset * unset $a
echo $a
Exercises
Set A:
Set B:
1. Write a shell script to view contents of a file proceeding with line numbers.
2. Write a shell script to show the list of users logged into the system.
3. Write a shell script to append the contents of one file to the end of another file.
4. Write a shell script to display file in reverse order.
5. Write a shell script to accept a file name and display number of words in a file.
(use wc command)
6. Write a shell script to accept a directory name and display its contents.
(use ls command)
7. Write a shell script to find size of given file.
8. Write a shell script to print out the length of longest (number of characters) line in a file.
9. Write a shell script to display the file names that matches the given pattern.
10. Write a shell script to accept a file name and a pattern. Display lines from the file in which the
pattern is present along with line number. (use grep command)
11. Write a shell script to accept a name, and create a copy of it named as this name- (hypen)copy
in the same directory . (use cp command)
12. Write a shell script that displays a list of files in current directory to which the user has read, write
and execute permissions.
80
SET C:
1. Write a shell script to display the lines that are not matched with the specified search sting
pattern.
2. Write a shell script to copy all files of the source directory to the destination directory.
Assignment Evaluation
81
Assignment 8
Aim: To study different conditional statements and command line arguments in shell
programming.
Pre-requisite: Knowledge of Linux commands and vi/ emac editor.
82
if..elif..else..fi statement if [ expression1 ] Script to check if an input number is
(Else If ladder) then positive, zero or negative:
use multiple conditions in statement1 echo “Enter a number”
one if-else block, then elif statement2 read num
keyword is used in shell. If . if [ $num -gt 0 ]
expression1 is true then it elif [ expression2 ] then
executes statement 1 and 2, then echo “It is a positive number” elif [
and this process continues. statement3 $num -eq 0 ]
If none of the condition is statement4 then
true then it processes else . echo “num is equal to zero” else
part else echo “It is not a positive integer”
statement
fi
if..then..else..if..then..fi..fi. if [ expression1 ] Script to illustrate use of nested if
.(Nested if) then else
Nested if-else block can be statement1
used when, one condition is statement2 echo "Enter Your Country:"
satisfies then it again checks . read cn
another condition. In the else
syntax, if expression1 is if [ expression2 ] if [$cn -eq 'India']
false then it processes else then then
part, and again expression2 statement3 echo "Enter Your State:"
will be check. . read st
fi if [$st -gt 'Gujarat']
then
echo "Welcome to Gujarat"
elif
echo "You are Not Gujarati"
fi
elif
echo "Other Country"
fi
switch statement case $[ variable_name ] in Script to illustrate Case Statement
case statement works as a value1) Example
switch statement if Statement 1
specified value match ;; echo "Enter Country Code:"
with the pattern then it value2) read co
will execute a block of Statement 2
that particular pattern. ;; case $co in
When a match is found all value3) 'IN') echo "India"
of the associated Statement 3 ;;
statements until the ;; 'PK') echo "Pakistan"
double semicolon (;;) is value4) ;;
executed. Statement 4 *) echo "Enter Vailid Country Code"
A case will be terminated ;; ;;
when the last command is valueN) esac
83
executed. Statement N
If there is no match, the ;;
exit status of the case is zero *)
Default Statement
;;
esac
File-based condition • -a file Returns true if file Script to illustrate file based
File-based conditions are exists conditions.
unary expressions and • -b file Returns true if file ls -l
often used to examine a exists and is a block special read -p "Enter a file name: " filename
status of a file. file if [ -e $filename ]
• -c file Returns true if file then
exists and is a character echo "file exists!"
special file if [ -r $filename ]
• -d file Returns true if file then
exists and is a directory status="readable "
• -e file Returns true if file fi
exists if [ -w $filename ]
• -r file Returns true if file then
exists and is readable status=$status"writable "
• -s file Returns true if file fi
exists and has a greater size if [ -x $filename ]
that zero then
status=$status"executable"
• -s file Returns true if file
fi
exists and has a greater size
echo "file permission: "$status
that zero
else
• -w file Returns true if file
echo "file does not exist"
exists and is writable
fi
• -x file Returns true if file
exists and is executable
• -N file Returns true if the
file exists and has been
modified since it was last
read
Arithmetic-based • -eq Equal Script to illustrate arithmetic based
Condition • -ge Greater Than conditions
or Equal read -p "Enter an integer: " int1
• -gt Greater Than if [ $int1 -eq 0 ]
• -le Less Than or then
Equal echo "Zero"
• -lt Less Than elif [ $int1 -lt 0 ]
• -ne Not Equal then
echo "Negative"
else
if [ $((int1%2)) -eq 0 ]
then
84
echo "Even"
else
echo "Odd"
fi
fi
String-based Condition • == Returns true if Script to illustrate string based
The string-based the strings are equal conditions
condition returns a • != Returns true if read -p "First String: " str1
binary expression as a the strings are not read -p "Second String: " str2
result meaning, it returns equal if [ -z "$str1" ]
true if the specified • -n Returns true if the then
condition is satisfied string to be tested is echo "The 1st string is null"
otherwise, it returns not null elif [ -z "$str2" ]
false. • -z Returns true if the then
string to be tested is echo "The 2nd string is null"
null else
if [ $str1 == $str2 ]
then
echo "The strings are equal"
else
echo "The strings are not equal"
fi
fi
85
Within the command script, the passed parameters are accessible using ‘positional parameters’. These
range from $0 to $9, where $0 refers to the name of the command itself, and $1 to $9 are the first through
to the ninth parameter, depending on how many parameters were actually passed.
Example:
$ sh welcome fybca
Example : Let’s create a shell script with name “command_line_agruments.sh”, it will show the command
line argruments that were supplied and count number of agruments, value of first argument and Process
ID (PID) of the Script.
86
linuxtvina@localhost:~$ ./command_line_agruments.sh Linux AIX HPUX VMware
There are 4 arguments specified at the command line
The arguments supplied are: Linux AIX HPUX VMware
The first argument is: Linux
The Process ID of the script is: 16369
The new first argument after the first shift is: AIX
The new first argument after the second shift is: HPUX
Exercises
Set A:
1. Write a shell script to check whether two numbers are same or different.
2. Write a shell script to check whether given number is odd or even.
3. Write a shell script to display “Good Morning”, “Good afternoon” , and “Good Evening”
depending on the hour .
4. Write a shell script to test a given file and return a message whether the file is a block device, a
character device or a normal file.
5. Write a shell script that accepts file name as argument and converts all of them to uppercase,
provided they exist in the current directory.
6. Write a shell script that accept directory name, if directory does not exist then it will create
directory of same name.
Set B:
1. Write a shell script to accept argument string on command line, and display present working
directory if argument string is “current” ,display parent directory if argument string is “parent” and
display the contents of root directory if argument string is “root” .
2. Write a shell script to accept an extension name such as txt on command line and display the
contents of all files with this extension, if there exists a file with this extension or give appropriate
message.
3. Write a shell script to accept as argument an extension name such as .txt and move the contents of
all files with this extension to a directory by the same name.
4. Write a shell script to accept a file name, and display file details if the file exists and a suitable
message if it does not.
5. Write a shell script which receives two file names as arguments. It should check whether the two
file contents are same or not. If they are same then second file should be deleted.
6. Write a shell script to check whether file is readable, writable or both or executable.
Set C:
1. Write a shell script that computes the gross salary of a employee according to the following rules:
i) If basic salary is < 1500 then HRA =10% of the basic and DA =90% of the basic.
ii) If basic salary is >=1500 then HRA =Rs500 and DA=98% of the basic
The basic salary is entered interactively through the key board.
2. Write a shell script that accepts a file name, starting and ending line numbers as arguments and
displays all the lines between the given line numbers.
3. Write a shell script that accept number and display whether that number is single digit, two digit
or three digit.
87
4. Write menu driven program to perform arithmetic operations like +, - , *, /
5. Write menu driven program to perform the following tasks
a) Show today’s date and time
b) Show files in current working directory.
c) Show calendar
d) Start editor to write letters
6. Write menu driven program to perform the following tasks
a) Create directory
b) Creating file
c) Displaying contents of file
d) Copying file into another file
e) Displaying files in directory
Assignment Evaluation
88
Assignment 9
Looping control structure, also known as Repetition control structure, is a type of control structure in
programming languages that is used to simplify repetitive or recursive tasks. The following are looping
control structures which can be used in shell programming
• while statement
• until statement
• for statement
To alter the flow of loop statements, two commands are used they are,
• break
• continue
89
a=0
Exercises
Set A:
1. Write a shell script to find factorial of number.
2. Write a shell script to find sum of digits.
3. Write a shell script to print multiplication table using command line arguments.
4. Write a shell script sum.sh that takes an unspecified number of command line arguments (up to 9) of
int and finds their sum. Modify the code to add a number to the sum only if the number is greater than
10.
5. Write a shell script that accepts two integers as its arguments and computers the value of first number
raised to the power of the second number.
6. Write a shell script to display first 10 odd numbers and their sum.
Set B:
1. Write a shell script which will print the numbers 1 - 10 (each on a separate line) and whether they are
even or odd.
2. Write a shell script to display all the *.conf file that begins with either a, b, or, c or d under / etc
directory.
3. Write a shell script to display days of week and adds “(WEEKEND)” to Sat and Sun, and “(weekday)”
to rest of the days. Output should be following:
Day 1 : Mon (weekday)
90
Day 6 : Sat (WEEKEND)
Day 7 : Sun (WEEKEND)
4. Write a shell script that will report the number of lines in each file within the current directory.
5. Write a shell script that accepts any number of arguments and prints them in a reverse order.
6. Write a shell script which will take a single command line argument (a directory) and will print
each entry in that directory. If the entry is a file it will print its size. If the entry is a directory it will print
how many items are in that directory.
Set C :
1. Write a shell script that takes a name of a folder as a command line argument, and produce a file
that contains the names of all sub folders with size 0 (that is empty sub folders)
2. Write a shell script that takes a name of a folder, and delete all sub folders of size 0
3. Write a shell script that will take an input file and remove identical lines (or duplicate lines from
the file)
4. Write a shell script that deletes all lines containing a specified word in one or more
files supplied as arguments to it.
5. Write a shell script which accepts a filename, displays menu with following options, accepts user
choice as number and takes appropriate action
a) Display the file contents
b) Display the file Size in blocks
c) Display the number of words in file
d) Display last five lines of the file
e) Display first ten lines of the file
6. Write a shell script that displays menu with following options, accepts user choice as number and
takes appropriate actions
a) Displays the No of users logged in
b) Display the login id of user logged i
c) Display the present working directory
d) Display the home directory of logged in user
e) Display the path
Assignment Evaluation
91