UL Lab Manual
UL Lab Manual
• Step 2
After downloading double click on installer and start installation for Virtual Box
• Step 3
It will ask where to install Virtual Box select directory path and click next
• Step 4
It will ask to select features select as per requirement and click on next
• Step 5
Now Virtual Box is ready for installation click on INSTALL
• Step 6
Now Oracle Virtual Box is successfully installed on our system
Ubuntu Installation process
• Step 1
Download Ubuntu 20.04.1 LTS from ubuntu from official website:
https://ubuntu.com/download/desktop
• Step 2
Click on new on Oracle VM Select Type and Version of OS
• Step 3
Go to settings => Storage => Select ISO image of Ubuntu we downloaded from website
• Step 4
Select language
• Step 5
Select keyboard layout
• Step 6
Click on continue
• Step 7
Click on Install
• Step 8
Setup username and password for system
• Step 9
Installation completed
Conclusion: VirtualBox is a general-purpose virtualization tool for for desktop, and embedded
use, that allows users and administrators to easily run multiple guest operating systems on a
single machine.
EXPERIMENT 2
Theory:
Sr Command Description Options
No.
1 echo echo command in Linux is used to display line -e here enables the
of text/string that are passed as an argument . interpretation of
This is a built-in command that is mostly used backslash escapes
in shell scripts and batch files to output status \b : it removes all the
text to the screen or a file. spaces in between the
text
2 clear clear is a standard Unix computer operating In order to clear the
system command that is used to clear the terminal press [ctrl+l]
terminal screen. This command first looks for a and for GNOME
terminal type in the environment and after that, terminal in ubuntu
it figures out the terminfo database for how to 18.04 press [shift +
clear the screen. And this command will ignore ctrl + alt + c]
any command-line parameters that may be
present. Also, the clear command doesn’t take
any argument and it is almost similar to cls
command on a number of other Operating
Systems.
3 exit exit command in linux is used to exit the shell exit n : Using “sudo
where it is currently running. It takes one more su” we are going to
parameter as [N] and exits the shell with a return the root directory and
of status N. If n is not provided, then it simply then exit the root
returns the status of last command that is directory with a return
executed. status of 5. After
returning it will show
how to display the
return status code.
4 date date command is used to display the system date %d shows current day
and time. date command is also used to set date %m shows current
and time of the system. By default the date month
command displays the date in the time zone on %y shows current
which unix/linux operating system is year
configured.You must be the super-user (root) to
change the date and tim
5 time time command in Linux is used to execute a
command and prints a summary of real-time, time -p : This option
user CPU time and system CPU time spent by is used to print time in
executing a command when it terminates. ‘real‘ POSIX format
time is the time elapsed wall clock time taken
by a command to get executed, while ‘user‘ and
‘sys‘ time are the number of CPU seconds that
command uses in user and kernel mode
respectively.
6 uptime Uptime is a command that returns information Using option -s will
about how long your system has been running display the date/time
together with the current time, number of users since when the system
with running sessions, and the system load has been running.
averages for the past 1, 5, and 15 minutes. It can
also filter the information displayed at once Using -p Show
depending on your specified options. uptime in pretty
format
7 Cal If a user wants a quick view of calendar in Linux cal 04 2000 : Shows
terminal, cal is the command for you. By calendar of selected
default, cal command shows current month month and year.
calendar as output. cal 2020 : Shows the
cal command is a calendar command in Linux whole calendar of the
which is used to see the calendar of a specific year.
month or a whole year.
8 tty Linux operating system represents everything in -s, –silent, –quiet :
a file system, the hardware devices that we Prints nothing, only
attach are also represented as a file. The returns an exit status.
terminal is also represented as a file. There a
command exists called tty which displays
information related to terminal. The tty –help : It will display
command of terminal basically prints the file the help message and
name of the terminal connected to standard exit.
input. tty is short of teletype, but popularly –version : Prints the
known as a terminal it allows you to interact version information
with the system by passing on the data (you and exits.
input) to the system, and displaying the output
produced by the system.
9 man man command in Linux is used to display the man command gives
user manual of any command that we can run manual for the given
on the terminal. It provides a detailed view of command
the command which includes NAME,
SYNOPSIS, DESCRIPTION, OPTIONS,
EXIT STATUS, RETURN VALUES,
ERRORS, FILES, VERSIONS, EXAMPLES,
AUTHORS and SEE ALSO.
10 which which command in Linux is a command which which -a : This option
is used to locate the executable file associated print all matching
with the given command by searching it in the pathnames of each
path environment variable. It has 3 return status argument.
as follows:
• 0 : If all specified commands are found
and executable.
• 1 : If one or more specified commands
is nonexistent or not executable.
• 2 : If an invalid option is specified.
11 history history command is used to view the previously
executed command. This feature was not
available in the Bourne shell. Bash and Korn
support this feature in which every command
executed is treated as the event and is associated
with an event number using which they can be
recalled and changed if required. These
commands are saved in a history file. In Bash
shell history command shows the whole list of
the command.
11 Id id command in Linux is used to find out user -g : Print only the
and group names and numeric ID’s (UID or effective group id.
group ID) of the current user or any other user -G : Print all Group
in the server. This command is useful to find out ID’s.
the following information as listed below: -n : Prints name
instead of number.
• User name and real user id.
• Find out the specific Users UID. -r : Prints real ID
• Show the UID and all groups associated instead of numbers.
with a user. -u : Prints only the
• List out all the groups a user belongs to. effective user ID.
• Display security context of the current –help : Display help
user. messages and exit.
–version : Display the
version information
and exit.
12 pwd pwd stands for Print Working Directory. It pwd -L: Prints the
prints the path of the working directory, starting symbolic path.
from the root. pwd -P: Prints the
pwd is shell built-in command(pwd) or an actual path.
actual binary(/bin/pwd).
$PWD is an environment variable which stores
the path of the current directory.
This command has two flags.
13 whoami whoami command is used both in Unix
Operating System and as well as in Windows
Operating System.
• It is basically the concatenation of the
strings “who”,”am”,”i” as whoami.
• It displays the username of the current
user when this command is invoked.
• It is similar as running the id command
with the options -un.
14 ping PING (Packet Internet Groper) command is -v to ping version
used to check the network connectivity between installed
host and server/host. This command takes as
input the IP address or the URL and sends a data -c to control number
packet to the specified address with the message of ping
“PING” and get a response from the server/host
this time is recorded which is called latency.
Fast ping low latency means faster connection.
Ping uses ICMP(Internet Control Message
Protocol) to send an ICMP echo message to the
specified host if that host is available then it
sends ICMP reply message. Ping is generally
measured in millisecond every modern
operating system has this ping pre-installed.
15 ifconfig ifconfig(interface configuration) command is -a : This option is
used to configure the kernel-resident network used to display all the
interfaces. It is used at the boot time to set up
the interfaces as necessary. After that, it is interfaces available,
usually used when needed during debugging or even if they are down.
when you need system tuning. Also, this
command is used to assign the IP address and -s : Display a short
netmask to an interface or to enable or disable a list, instead of details.
given interface.
16 pr In Linux/Unix pr command is used to prepare a pr [options][filename]
file for printing by adding suitable footers,
headers, and the formatted text. pr command
actually adds 5 lines of margin both at the top
and bottom of the page. The header part shows
the date and time of the last modification of the
file with the file name and the page number.
17 ip ip command in Linux is present in the net-tools -address: This option
which is used for performing several network is used to show all IP
administration tasks. IP stands for Internet addresses associated
Protocol. This command is used to show or on all network
manipulate routing, devices, and tunnels. It is devices.
similar to ifconfig command but it is much more
powerful with more functions and facilities -link: It is used to
attached to it. ifconfig is one of the deprecated display link layer
commands in the net-tools of Linux that has not information, it will
been maintained for many years. ip command is fetch characteristics
used to perform several tasks like assigning an of the link layer
address to a network interface or configuring devices currently
network interface parameters. available. Any
It can perform several other tasks like networking device
configuring and modifying the default and static which has a driver
routing, setting up tunnel over IP, listing IP loaded can be
addresses and property information, modifying classified as an
the status of the interface, assigning, deleting available device.
and setting up IP addresses and routes.
Output screenshots:
• Command echo
• Command exit
• Command date
Fig.4-time command
• Command uptime
Fig.5-uptime command
• Command cal
Fig.6-cal command
• Command tty
Fig.7-tty command
• Command man
Fig.8-man command
• Command which
Fig.9-which command
• Command history
Fig.10-history command
• Command id
Fig.11-id command
• Command pwd
Fig.12-pwd command
• Command whoami
Fig.13-whoami command
• Command ping
Fig.14-ping command
• Command ifconfig
Fig.15-ifconfig command
• Command pr
Fig.16-pr command
• Command ip
Fig.17-ip command
Conclusion: Unix commands are inbuilt programs that can be invoked in multiple ways. We
worked with these commands interactively from a Unix terminal. A Unix terminal is a graphical
program that provides a command-line interface using a shell program.
EXPERIMENT 3
Theory:
Vi editor Installation
Sr Command Description
No.
1 i Insert at cursor (goes into insert mode)
2 a Write after cursor (goes into insert mode)
3 A Write at the end of line (goes into insert mode)
4 ESC Terminate insert mode
5 u Undo last change
6 U Undo all changes to the entire line
7 o Open a new line (goes into insert mode)
8 dd Delete line
9 3dd Delete 3 lines.
10 D Delete contents of line after the cursor
11 C Delete contents of a line after the cursor and insert new text. Press ESC key to
end insertion
11 dw Delete word
12 4dw Delete 4 words
13 x Delete character at the cursor
14 r Replace character
15 R Overwrite characters from cursor onward
16 s Substitute one character under cursor continue to insert
17 S Substitute entire line and begin to insert at the beginning of the line
18 ~ Change case of individual character
Output screenshots:
Before After
• i
• a
• A
• ESC
• u
• U
• o
• dd
• 3dd
• D
• C
• dw
• 4dw
• x
• r
• R
• s
• S
• ~
• Some commands for saving and closing file
Command Description
Shift+zz Save the file and quit
:w Save the file but keep it open
:q Quit without saving
: wq Save the file and quit
Output:
Before After
• Shift+zz
• :w
• :q
• :wq
Conclusion: VI editor to edit an existing file or to create a new file from scratch VI editor
works in two modes, Command and Insert, Command mode takes the user commands,
and the Insert mode is for editing text. t is more user-friendly than other editors
EXPERIMENT 4
Aim: To study UNIX File System and file system management commands
Lab Outcome: 8. ITL402.3 Apply Unix commands for system administrative tasks such as file
system management and user management.
Theory:
A file system is a logical collection of files on a partition or disk. A partition is a container for
information and can span an entire hard drive if desired.
Your hard drive can have various partitions which usually contain only one file system, such as
one file system housing the /file system or another containing the /home file system.
One file system per partition allows for the logical maintenance and management of differing file
systems.
Everything in Unix is considered to be a file, including physical devices such as DVD-ROMs,
USB devices, and floppy drives.
Directory Structure
Unix uses a hierarchical file system structure, much like an upside-down tree, with root (/) at the
base of the file system and all other directories spreading from there.
A Unix filesystem is a collection of files and directories that has the following properties −
• It has a root directory (/) that contains other files and directories.
• Each file or directory is uniquely identified by its name, the directory in which it resides,
and a unique identifier, typically called an inode.
• By convention, the root directory has an inode number of 2 and the lost+found directory
has an inode number of 3. Inode numbers 0 and 1 are not used. File inode numbers can
be seen by specifying the -i option to ls command.
• It is self-contained. There are no dependencies between one filesystem and another.
The directories have specific purposes and generally hold the same types of information for easily
locating files. Following are the directories that exist on the major versions of Unix
Sr Command Description
No.
1 / This is the root directory which should contain only the directories needed at the
top level of the file structure
2 /bin This is where the executable files are located. These files are available to all
users
3 /dev These are device drivers
4 /etc Supervisor directory commands, configuration files, disk configuration files,
valid user lists, groups, ethernet, hosts, where to send critical messages
5 /lib Contains shared library files and sometimes other kernel-related files
6 /boot Contains files for booting the system
7 /home Contains the home directory for users and other accounts
8 /mnt Used to mount other temporary file systems, such as cdrom and floppy for
the CD-ROM drive and floppy diskette drive, respectively
9 /proc Contains all processes marked as a file by process number or other information
that is dynamic to the system
10 /tmp Holds temporary files used between system boots
11 /usr Used for miscellaneous purposes, and can be used by many users. Includes
administrative commands, shared files, library files, and others
11 Typically contains variable-length files such as log and print files and any other
/var
type of file that may contain a variable amount of data
12 /sbin Contains binary (executable) files, usually for system administration. For
example, fdisk and ifconfig utlities
13 /kernel Contains kernel files
Navigating the File System
Sr Command Description
No.
1 cat filename Displays a filename
2 cd dirname Moves you to the identified directory
3 cp file1 file2 Copies one file/directory to the specified location
4 file filename Identifies the file type (binary, text, etc)
5 find filename Finds a file/directory
dir
6 head filename Shows the beginning of a file
7 less filename Browses through a file from the end or the beginning
8 ls dirname Shows the contents of the directory specified
9 mkdir Creates the specified directory
dirname
10 more Browses through a file from the beginning to the end
filename
11 mv file1 file2 Moves the location of, or renames a file/directory
12 pwd Shows the current directory the user is in
13 rm filename Removes a file
14 rmdir Removes a directory
dirname
15 tail filename Shows the end of a file
16 touch Creates a blank file or modifies an existing file or its attributes
filename
17 whereis Shows the location of a file
filename
Output screenshots:
• cat command
• cd command
• cp command
• file command
• find filename dir
• head filename
• less filename
• ls dirname
• mkdir dirname
• more filename
• mv file1 file2
• pwd
• rm filename
• rmdir dirname
• tail filename
• touch filename
• whereis filename
Conclusion: Unix is an operating system that handles files in an organized way. With all the
commands and functions managing files is very easy. The file system of Unix is hence
considered to be one of the most user-friendly file systems.
EXPERIMENT 5
Lab Outcome: 8. ITL402.3 Apply Unix commands for system administrative tasks such as file
system management and user management.
Theory:
There are three types of accounts on a Unix system −
Root account
This is also called superuser and would have complete and unfettered control of the system. A
superuser can run any commands without any restriction. This user should be assumed as a system
administrator.
System accounts
System accounts are those needed for the operation of system-specific components for example
mail accounts and the sshd accounts. These accounts are usually needed for some specific
function on your system, and any modifications to them could adversely affect the system.
User accounts
User accounts provide interactive access to the system for users and groups of users. General
users are typically assigned to these accounts and usually have limited access to critical system
files and directories.
Unix supports a concept of Group Account which logically groups a number of accounts. Every
account would be a part of another group account. A Unix group plays important role in handling
file permissions and process management.
Create a Group
We will now understand how to create a group. For this, we need to create groups before creating
any account otherwise, we can make use of the existing groups in our system. We have all the
groups listed in /etc/groups file.
All the default groups are system account specific groups and it is not recommended to use them
for ordinary accounts. So, following is the syntax to create a new group account
Delete a Group
We will now understand how to delete a group. To delete an existing group, all you need is
the groupdel command and the group name. To delete the financial group, the command is −
$ groupdel developer
This removes only the group, not the files associated with that group. The files are still accessible
by their owners.
Create an Account
Let us see how to create a new account on your Unix system. Following is the syntax to create a
user's account −
useradd -d homedir -g groupname -m -s shell -u userid accountname
Sr Command Description
No.
1 who Who command without any input arguments, will display system’s
information like user name, login time, terminal of user, and also the host
name on the system.
2 whoami It displays the username of the current user when this command is invoked.
3 su In Linux, the su command (switch user) is used to run a command as a different
user.
4 sudo The sudo command temporarily elevates privileges allowing users to complete
sensitive tasks without logging in as the root user.
5 login login is used when signing onto a system. It can also be used to switch from one
user to another at any time (most modern shells have support for this feature
built into them, however).
6 exit exit command in linux is used to exit the shell where it is currently running. It
takes one more parameter as [N] and exits the shell with a return of status N. If
n is not provided, then it simply returns the status of last command that is
executed.
7 passwd The passwd command changes passwords for user accounts. A normal user may
only change the password for his/her own account, while the superuser may
change the password for any account. passwd also changes the account or
associated password validity period
8 useradd To add/create a new user, all you’ve to follow the command ‘useradd‘ or
‘adduser‘ with ‘username’. The ‘username’ is a user login name, that is used by
user to login into the system
9 usermod usermod command or modify user is a command in Linux that is used to change
the properties of a user in Linux through the command line
10 groupadd In Linux, groups are used to organize and administer user accounts. The primary
purpose of groups is to define a set of privileges such as reading, writing, or
executing permission for a given resource that can be shared among the users
within the group.
11 groupmod The groupmod command modifies the definition of the specified GROUP by
modifying the appropriate entry in the group database.
11 This is use to delete group
groupdel
12 gpasswd Set password for group
13 chown To change owner, change the user and/or group ownership of each given File to
a new Owner. Chown can also change the ownership of a file to match the
user/group of an existing reference file.
14 chage chage command is used to view and change the user password expiry
information. This command is used when the login is to be provided for a user
for limited amount of time or when it is necessary to change the login password
time to time
15 chgrp chgrp command in Linux is used to change the group ownership of a
file or directory. All files in Linux belong to an owner and a group. You
can set the owner by using “chown” command, and the group by the
“chgrp” command.
16 chfn chfn command in Linux allows you to change a user’s name and
other details easily. chfn stands for Change finger. Basically, it is
used to modify your finger information on Linux system. This
information is generally stored in the file /etc/passwd that includes
user’s original name, work phone number etc
Output screenshots:
• who/whoami
• su command
• sudo command
• login command
• Useradd/adduser command
• passwd command
• usermod command
• groupadd command
• groupmod
• groupdel
• gpasswd command
• chown command
• chage command
• chgrp command
• chfn command
Conclusion: we used both GUI or Terminal for User Administration in Linux User management
we can create, disable and remove user accounts using Linux admin commands. we can
add/delete a user to a user group.
EXPERIMENT 6
Starting a Process
When you start a process (run a command), there are two ways you can run it −
• Foreground Processes
• Background Processes
Foreground Processes
By default, every process that you start runs in the foreground. It gets its input from the keyboard
and sends its output to the screen.
You can see this happen with the ls command. If you wish to list all the files in your current
directory, you can use the following command −
$ls ch*.doc
This would display all the files, the names of which start with ch and end with .doc −
ch01-1.doc ch010.doc ch02.doc ch03-2.doc
ch04-1.doc ch040.doc ch05.doc ch06-2.doc
ch01-2.doc ch02-1.doc
The process runs in the foreground, the output is directed to my screen, and if the ls command
wants any input (which it does not), it waits for it from the keyboard.
While a program is running in the foreground and is time-consuming, no other commands can be
run (start any other processes) because the prompt would not be available until the program
finishes processing and comes out.
Background Processes
A background process runs without being connected to your keyboard. If the background process
requires any keyboard input, it waits.
The advantage of running a process in the background is that you can run other commands; you
do not have to wait until it completes to start another!
The simplest way to start a background process is to add an ampersand (&) at the end of the
command.
$ls ch*.doc &
This displays all those files the names of which start with ch and end with .doc −
ch01-1.doc ch010.doc ch02.doc ch03-2.doc
ch04-1.doc ch040.doc ch05.doc ch06-2.doc
ch01-2.doc ch02-1.doc
Here, if the ls command wants any input (which it does not), it goes into a stop state until we
move it into the foreground and give it the data from the keyboard.
That first line contains information about the background process - the job number and the process
ID. You need to know the job number to manipulate it between the background and the
foreground.
Press the Enter key and you will see the following −
[1] + Done ls ch*.doc &
$
The first line tells you that the ls command background process finishes successfully. The second
is a prompt for another command.
Memory Partitioning
The simplest form of memory management is splitting up the main memory into
multiple logical spaces called partition. Each partition is used for separate program.
There are 2 types of memory partitioning:-
There are two different forms of multiple partition allocation, which is fixed partitioning
and variable partitioning. Fixed partitioning divides memory up into many fixed
partitions which cannot be change. However, variable partitioning is more flexible
because the partitions vary dynamically in the later as processes come and go. Variable
partitioning (Variable memory) has been used in UNIX.
Overlays
Program will be place into memory during execution. However, a large program will
divide into small pieces and loading the pieces as they needed. Overlays will replace the
new pieces with the program which is unused. UNIX is using this technique to run a new
program by fork the running process which is also known as fork-exec.
Swapping
Swapping consists of bringing in each process in physical memory entirely and running
it. When the process is no longer in use, the process will be terminated or is swapped
out to disk.
Initially only process A is in memory. Then process B is swapped into memory from disk.
After that, process A terminates or swapped out to disk. Then process C is swapped into
the free space.
• Process management commands
Sr Command Description
No.
1 bg To send a process to the background
2 fg To run a stopped process in the foreground
3 top Details on all Active Processes
4 ps Give the status of processes running for a user
5 ps PID Gives the status of a particular process
6 pidof Gives the Process ID (PID) of a process
7 kill PID Kills a process
8 nice Starts a process with a given priority
9 renice Changes priority of an already running process
10 xkill Command xkill is used to kill a process on X server without passing process
name or PID. It forces the X server to close the communication with its clients,
which ultimately kill its clients by its X resource. In short, xkill instructs X
server to terminate client.
11 killall killall sends a signal to all processes running any of the specified commands. If
no signal name is specified, SIGTERM is sent.
Output:
• Process management commands
• bg command
• fg command
• top command
• ps command
• ps pid
• pidof command
• kill pid
• nice command
• renice command
• xkill command
• killall command
• free command
• top command
• du command
• vmstat command
• dmidecode command
• sar command
• pagesize command
Conclusion: Implemented the basic and advanced process management and memory management
commands on the Ubuntu terminal. Learnt how see the states and description (along with in depth
description) of various processes, how to execute and kill an application, how change the nice and the
priority value of the process.
EXPERIMENT 7
Theory:
A Unix shell is a command-
Shell Types
In Unix, there are two major types of shells −
1) Bourne shell − If you are using a Bourne-type shell, the $
character is the default prompt. The Bourne Shell has the
following subcategories −
a) Bourne shell (sh)
b) Korn shell (ksh)
c) Bourne Again shell (bash)
d) POSIX shell (sh)
2) C shell − If you are using a C-type shell, the %
character is the default prompt. The different C-
type shells follow −
a) C shell (csh)
b) TENEX/TOPS C shell (tcsh)
Bourne shell was the first shell to appear on Unix systems, thus it is referred to as "the shell".
Bourne shell is usually installed as /bin/sh on most versions of Unix. For this reason, it is the
shell of choice for writing scripts that can be used on different versions of Unix.
The prompt, $, which is called the command prompt, is issued by the shell. While
the prompt is displayed, you can type a command.
Shell reads your input after you press Enter. It determines the command you
want executed by looking at the first word of your input. A word is an
unbroken set of characters. Spaces and tabs separate words.
var.sh
#!/bin/sh
MY_MESSAGE="Hello World"
echo $MY_MESSAGE
This assigns the string "Hello World" to the variable MY_MESSAGE then echoes out the value
of the variable.
Note that we need the quotes around the string Hello World. Whereas we could get away
with echo Hello World because echo will take any number of parameters, a variable can only
hold one value, so a string with spaces must be quoted so that the shell knows to treat it all as
one. Otherwise, the shell will try to execute the command World after
assigning MY_MESSAGE=Hello
The shell does not care about types of variables; they may store strings, integers, real numbers -
anything you like.
People used to Perl may be quite happy with this; if you've grown up with C, Pascal, or worse
yet Ada, this may seem quite strange.
In truth, these are all stored as strings, but routines which expect a number can treat them as
such.
If you assign a string to a variable then try to add 1 to it, you will not get away with it:
$ x="hello"
$ expr $x + 1
expr: non-numeric argument
$
This is because the external program expr only expects numbers. But there is no syntactic
difference between:
MY_MESSAGE="Hello World"
MY_SHORT_MESSAGE=hi
MY_NUMBER=1
MY_PI=3.142
MY_OTHER_PI="3.142"
MY_MIXED=123abc
Note though that special characters must be properly escaped to avoid interpretation by the shell.
This is discussed further in Chapter 6, Escape Characters.
We can interactively set variable names using the read command; the following script asks you
for your name then greets you personally:
var2.sh
#!/bin/sh
echo What is your name?
read MY_NAME
echo "Hello $MY_NAME - hope you're well."
Mario Bacinsky kindly pointed out to me that I had originally missed out the double-quotes in
line 3, which meant that the single-quote in the word "you're" was unmatched, causing an error.
It is this kind of thing which can drive a shell programmer crazy, so watch out for them!
This is using the shell-builtin command read which reads a line from standard input into the
variable supplied.
Note that even if you give it your full name and don't use double quotes around
the echo command, it still outputs correctly. How is this done? With
the MY_MESSAGE variable earlier we had to put double quotes around it to set it.
What happens, is that the read command automatically places quotes around its input, so that
spaces are treated correctly. (You will need to quote the output, of course - e.g. echo
"$MY_MESSAGE").
Scope of Variables
Variables in the Bourne shell do not have to be declared, as they do in languages like C. But if
you try to read an undeclared variable, the result is the empty string. You get no warnings or
errors. This can cause some subtle bugs - if you assign
MY_OBFUSCATED_VARIABLE=Hello
and then
echo $MY_OSFUCATED_VARIABLE
Then you will get nothing (as the second OBFUSCATED is mis-spelled).
There is a command called export which has a fundamental effect on the scope of variables. In
order to really know what's going on with your variables, you will need to understand something
about how this is used.
Create a small shell script, myvar2.sh:
myvar2.sh
#!/bin/sh
echo "MYVAR is: $MYVAR"
MYVAR="hi there"
echo "MYVAR is: $MYVAR"
#!/bin/sh
echo "What is your name?"
read USER_NAME
echo "Hello $USER_NAME"
echo "I will create you a file called $USER_NAME_file"
touch $USER_NAME_file
Think about what result you would expect. For example, if you enter "steve" as your
USER_NAME, should the script create steve_file?
Actually, no. This will cause an error unless there is a variable called USER_NAME_file. The
shell does not know where the variable ends and the rest starts. How can we define this?
The answer is, that we enclose the variable itself in curly brackets:
Conclusion: Implemented the basic and advanced process management and memory management
commands on the Ubuntu terminal. Learnt how see the states and description (along with in depth
description) of various processes, how to execute and kill an application, how change the nice and the
priority value of the process.
Operators in Shell Scripting
There are 4 basic operators in bash/shell scripting:
• Arithmetic Operators
• Relational Operators
• Boolean Operators
• Bitwise Operators
Relational Operators : Relational operators are those operators which defines the relation
between two operands. They give either true or false depending upon the relation. They are of
6 types:
• ‘==’ Operator : Double equal to operator compares the two operands. Its returns
true is they are equal otherwise returns false.
• ‘!=’ Operator : Not Equal to operator return true if the two operands are not equal
otherwise it returns false.
• ‘<' Operator : Less than operator returns true if first operand is lees than second
operand otherwse returns false.
• ‘<=' Operator : Less than or equal to operator returns true if first operand is less
than or equal to second operand otherwise returns false
• ‘>’ Operator : Greater than operator return true if the first operand is greater than
the second operand otherwise return false.
• ‘>=’ Operator : Greater than or equal to operator returns true if first operand is
greater than or equal to second operand otherwise returns false
Logical Operators : They are also known as boolean operators. These are used to perform
logical operations. They are of 3 types:
• Logical AND (&&) : This is a binary operator, which returns true if both the
operands are true otherwise returns false.
• Logical OR (||) : This is a binary operator, which returns true is either of the
operand is true or both the operands are true and returns false if none of then is
false.
• Not Equal to (!) : This is a uninary operator which returns true if the operand is
false and returns false if the operand is true.
Programs:
Scrpit1.sh
#! bin/sh
ls -l
pwd
Scrpit2.sh
#!/bin/sh
#This is my second script file
echo "Waht is your name"
read studentname
echo "Godd Morning, $studentname"
Name="Anmol Agnihotri"
echo "My self, $Name"
#readonly Name
Name="Naman Desai"
unset Name
echo $0
echo $$
Script3.sh
#!/bin/sh
echo "file name of current script is: $0"
echo "first parameter is: $1"
echo "second parameter is: $2"
echo "Quoted values are: $@"
echo "Quoted values are: $*"
echo "Total number of parameters are: $#"
for value in $*
do
echo $value
done
Script4.sh
#!bin/sh
#Aratmatic Operator
read -p 'Enter Value of A:' a
read -p 'Enter Value of B:' b
echo $a
echo $b
add=$((a+b))
echo "Addition of A and B is: $add"
sub=$((a-b))
echo "Subraction of A and B is: $sub"
mul=$((a*b))
echo "Multiplication of A and B is: $mul"
div=$((a/b))
echo "Division of A and B is: $div"
mod=$((a%b))
echo "Modulus of A and B is: $mod"
inc=$((++a))
echo "increment of A and B is: $inc"
dec=$((--b))
echo "decrement of A and B is: $dec"
Script5.sh
#!bin/sh
#Relational Operator
read -p 'Enter Value of A:' a
read -p 'Enter Value of B:' b
echo $a
echo $b
if(($a==$b))
then
echo "A is Euqal to B"
else
echo "A is not equal to B"
fi
if(($a!=$b))
then
echo "A is not Euqal to B"
else
echo "A is equal to B"
fi
if(($a<b))
then
echo "A is less than to B"
else
echo "A is not less than B"
fi
if(($a<=b))
then
echo "A is less than or equal to B"
else
echo "A is not less than B"
fi
if(($a>b))
then
echo "A is greater than B"
else
echo "A is not greater than B"
fi
if(($a>=b))
then
echo "A is greater equal than B"
else
echo "A is not greater than B"
fi
Script6.sh
#!bin/sh
#Logical Operator
read -p 'Enter Value of A:' a
read -p 'Enter Value of B:' b
echo $a
echo $b
if(($a=="true" && $b=="true"))
then
echo "Both the values are true"
else
echo "both are not true"
fi
if(($a=="true" || $b=="true"))
then
echo "Atlest one of them is true"
else
echo "none of them is true"
fi
if((!$a=="true"))
then
echo "A is False"
else
echo "A is true"
fi
if((!$b=="true"))
then
echo "B is False"
else
echo "B is true"
fi
Script7.sh
#!bin/sh
#Bitwise Operator
read -p 'Enter Value of A:' a
read -p 'Enter Value of B:' b
echo $a
echo $b
bitwiseand=$((a&b))
echo "Bitwise and of A and B is: $bitwiseand"
#Bitwiseor is |
bitwiseor=$((a|b))
echo "Bitwise OR of A and B is: $bitwiseor"
#Bitwisexor is ^
bitwisexor=$((a^b))
echo "Bitwise X OR of A and B is: $bitwisexor"
#Bitwisecomplement is ~
bitwisecomplement=$((~a))
echo "Bitwise Complement of A is: $bitwisecomplement"
#bitwiseleftshift is <<
bitwiseleftshift=$((a<<1))
echo "Bitwise Left Shift of A is: $bitwiseleftshift"
#Bitwiserightshift is >>
bitwiserightshift=$((a>>1))
echo "Bitwise Right Shift of A is: $bitwiserightshift"
Conclusion:
Implemented the basic shell scripting commands. Learnt the various ways to write
the program, view the program and execute the program. Learnt how to create
comments. Learnt how to set the compilers path. Learnt how to include and work
with loops and conditional statements. Learnt how to accept, store (in variables)
and print data. Learnt about variables and its types including the special variables.
Learnt with execution the working of the 5 types of operators and all the operators
that come under them.
EXPERIMENT 8
Problem Statement:
Write a shell script:
• Write a shell script to perform arithmetic operations.
• Write a shell script to calculate simple interest.
• Write a shell script to determine largest among three integer numbers.
• Write a shell script to determine a given year is leap year or not.
• Write a shell script to print multiplication table of given number using while statement.
• Write a shell script to search whether element is present is in the list or not.
Theory:
Shell supports a different type of variable called an array variable. This can hold multiple values at the
same time. Arrays provide a method of grouping a set of variables. Instead of creating a new name for
each variable that is required, you can use a single array variable that stores all the other variables.
All the naming rules discussed for Shell Variables would be applicable while naming arrays.
We can use a single array to store all the above mentioned names. Following is the simplest method of
creating an array variable. This helps assign a value to one of its indices.
array_name[index]=value
Here array_name is the name of the array, index is the index of the item in the array that you want to set,
and value is the value you want to set for that item.
name [0]="A"
name [1]="B"
name [2]="C"
name [3]="D"
name [4]="E"
As an example, the following commands –
or
name = (A B C D E)
After you have set any array variable, you access it as follows –
${array_name[index]}
echo "First Index: ${name[0]}"
echo "Second Index: ${name[1]}"
We can pass * or @ within the square parenthesis to get the value of all array / list variables
echo "All Index: ${name[@]}"
echo "All Index: ${name[*]}"
Programs:
• Program -1:
#!/bin/sh
#Arithmatic operator.
read -p 'Enter value of a:' a
read -p 'Enter value of b:' b
echo $a
echo $b add=$((a+b))
echo "The addition of a and b is, $add" sub=$((a-b))
echo "The subtraction of a and b is, $sub" mul=$((a*b))
echo "The multiplication of a and b is, $mul" div=$((a/b))
echo "The division of a and b is, $div" mod=$((a%b))
echo "The modulus of a and b is, $mod" inc=$((++a))
echo "The increment of is, $inc" dec=$((--a))
dec=$((--a))
echo "The decrement is, $dec"
• Program -2:
#!/bin/sh
echo " Enter the principle value: "
read p
echo " Enter the rate of interest:"
read r
echo " Enter the time period:"
read t
s=`expr $p \* $t \* $r / 100`
echo " The simple interest is "
echo $s
• Program -3:
#!/bin/sh
read -p "Enter your first integer number: " a
read -p "Enter your second integer number: " b
read -p "Enter your third integer number: " c
if [ $a -gt $b ] && [ $a -gt $c ]
then
echo $a "is greater"
elif [ $b -gt $a ] && [ $b -gt $c ]
then
echo $b "is greater"
else
echo $c "is greater"
fi
• Program -4:
#!/bin/sh
read -p "Enter year: " y
if [ $(( y % 400)) -eq 0 ]
then
echo $y "is a leap year"
elif [ $(( y % 100)) -eq 0 ]
then
echo $y "is not a leap year"
elif [ $(( y % 4)) -eq 0 ]
then
echo $y "is a leap year"
else
echo $y "is not a leap year"
fi
• Program 5
#!/bin/sh
read -p "Enter Number: " n
read -p "Enter range: " r
i=0
while [ $i -le $r ]
do
echo "$n x $i = `expr $n \* $i`"
i=`expr $i + 1 `
done
• Program 6
#Write a shell script to search whether element is present is in the
list or not.
#!/bin/sh
echo "Shell Script to search whether element is present is in the list
or not."
a[0]=1
a[2]=2
a[3]=3
a[4]=4
a[5]=5
#Print the value
echo "Display the element of Array using *: ${a[*]}"
echo "Display the element of Array using @: ${a[@]}"
#access element of array
echo "Accessing the element of and Array at a particular index"
echo " Value present at index 3 :${a[3]}"
#array initialization
b=(6 7 7 9 10)
echo "Element in array B: ${b[*]}"
read -p "Enter number to be search: " n
echo $n
for x in "${b[@]}"
do
if [ $x -eq $n ]
then
echo "Number is found"
break
fi
done
Output:
Program 1
Program 2:
Program 3:
Program 4:
Program 5:
Program 6:
Conclusion:
Implemented the basic shell scripting programs. Calculate simple interest using expressions, find
out the largest of the 3 input numbers by conditional branching, finding if or not a year is a leap
year using nested conditional branching, printed the multiplication table of given inputs using the
while loop and searching an element using the linear search method using loops, conditional
branching and checking equality within an array of elements.
EXPERIMENT 9
Problem Statement:
Write a shell script:
• Write a shell script to compare two strings.
• Write a shell script to read and check if the directory / file exists or not, if not make the
directory / file.
• Write a shell script to implement menu-driven calculator using case statement.
• Write a shell script to print following pattern:
*
**
***
****
• Write a shell script to perform operations on directory like: display name of current
directory; display list of directory contents; create another directory, write contents on that
and copy it to a suitable location in your home directory; etc.
Theory:
echo command in linux is used to display line of text/string that are passed as an argument .
This is a built in command that is mostly used in shell scripts and batch files to output status
text to the screen or a file.
Syntax :
echo [option] [string]
Displaying a text/string :
Syntax :
echo [string]
Options Description
-n do not print the trailing newline.
-e enable interpretation of backslash escapes.
\b backspace
\\ backslash
\n new line
\r carriage return
\t horizontal tab
\v vertical tab
Programs:
• Program -1:
#!/bin/sh
#Script to compare two strings
read -p "Enter String 1" a
read -p "Enter String 2" b
echo a
echo b
if [ $a == $b ]
then
echo "Strings are equal"
else
echo "String not equal"
fi
• Program -2:
#!/bin/sh
#Check if directory file exist, if not creat it
read -p "Enter file name: " f
read -p "Enter Directory name: " d
echo $f
echo $d
if [ -f "$f" ]
then
echo "Enterd file exist"
else
echo "Enterd file dose not exist"
touch "$f"
echo "New file created"
fi
if [ -d "$d" ]
then
echo "Enterd directory exist"
else
echo "Enterd directory dose not exist"
mkdir "$d"
echo "New directory created"
fi
• Program 3:
# !/bin/bash
• Program 4
#!/bin/sh
#Print following pattern
#*
#* *
#* * *
#* * * *
r=4
for((i=1; i<=r; i++))
do
for((j=1; j<=i; j++))
do
echo -n "* "
done
echo
done
• Program 5
a=0
while a==0
do
echo "Enter your choice"
echo "1 - Display name of the current directory"
echo "2 - Display list of directory contents"
echo "3 - Create another directory"
echo "4 - Write contents on that and copy it to a suitable
location in your home directory"
echo "5 - Exit"
read -p "Choice : " ch
case $ch in
1) pwd;;
2) ls;;
3) read -p "Enter name of your directory : " n
mkdir $n;;
4) read -p "Enter your source file : " s
read -p "Enter your destination file : " d
gedit $s
cp $s $d ;;
5) a=1
break;;
*)echo "Wrong choice entered ";;
esac
done
• Output 1:
• Output 2:
• Output 3:
• Output 4:
• Output 5:
Conclusion:
Implemented the basic shell scripting programs. programs. Learnt how to compare two strings,
how to create a non-existing directory, how to create a user input calculator, print patterns and
handle file data and file handling. Learnt the various applications of the echo command and all of
its following subsidies.
EXPERIMENT 10
Problem Statement:
Write a shell script:
• Write a script using grep command to find the number of words character, words and
lines in a file.
• Write ascriptusing egrep command to display list of specific type of files in the directory.
• Write a script using sed command to replace all occurrences of particular word in given a
file.
• Write a script using sedcommand to print duplicated lines in input.
Theory:
Grep is a Linux / Unix command-line tool used to search for a string of characters in a specified
file. The text search pattern is called a regular expression. When it finds a match, it prints the line
with the result. The grep command is handy when searching through large log files.
The grep command consists of three parts in its most basic form. The first part starts with grep,
followed by the pattern that you are searching for. After the string comes the file name that the
grep searches through.
• To Search a File
To print any line from a file that contains a specific pattern of characters, in our case phoenix in
the file sample2, run the command:
To search multiple files with the grep command, insert the filenames you want to search,
separated with a space character.
In our case, the grep command to match the word phoenix in three files sample,sample2,
and sample3
To search all files in the current directory, use an asterisk instead of a filename at the end of a
grep command.
grep nix *
The output shows the name of the file with nix and returns the entire line.
Grep allows you to find and print the results for whole words only. To search for the
word phoenix in all files in the current directory, append –w to the grep command.
As grep commands are case sensitive, one of the most useful operators for grep searches is -
i. Instead of printing lowercase results only, the terminal displays both uppercase and lowercase
results. The output includes lines with mixed case entries.
• To Search Subdirectories
To include all subdirectories in a search, add the -r operator to the grep command.
grep -r phoenix *
This command prints the matches for all files in the current directory, subdirectories, and the
exact path with the filename. In the example below, we also added the -w operator to show
whole words, but the output form is the same.
You can use grep to print all lines that do not match a specific pattern of characters. To invert
the search, append -v to a grep command.
The terminal prints all lines that do not contain the word used as a search criterion. Use -i to
ignore case to exclude completely the word used for this search:
The grep command prints entire lines when it finds a match in a file. To print only those lines
that completely match the search string, add the -x option.
The output shows only the lines with the exact match. If there are any other words or characters
in the same line, the grep does not include it in the search results. Do not forget to use quotation
marks whenever there is a space or a symbol in a search pattern.
Here is a comparison of the results without and with the -x operator in our grep comman
Sed Command in Linux/Unix with examples
SED command in UNIX is stands for stream editor and it can perform lot’s of function on file
like, searching, find and replace, insertion or deletion. Though most common use of SED
command in UNIX is for substitution or for find and replace. By using SED you can edit files
even without opening it, which is much quicker way to find and replace something in file, than
first opening that file in VI Editor and then changing it.
• SED is a powerful text stream editor. Can do insertion, deletion, search and
replace(substitution).
• SED command in unix supports regular expression which allows it perform complex
pattern matching.
Syntax:
sed OPTIONS... [SCRIPT] [INPUTFILE...]
#!/bin/sh
#Write a script using grep command to find the number of words
character, words and lines in a file
echo -e "\n Global Regular Expression pattern search"
grep -c lab ggwp.txt
echo -e "\n Searching for pattern and display in highlited
color"
grep --color -n "lab" ggwp.txt
grep -w lab ggwp.txt
echo -e "\n Display insesnsitve output"
grep -w -i Lab ggwp.txt
echo -e "\n Display count in output"
grep --count lab ggwp.txt
Write ascriptusing egrep command to display list of specific type of files in the directory
#ls | egrep -n "*.sh"
ls | egrep -n -i "*.Sh"
find . -name "*.sh" | egrep -i exp
Write a script using sed command to replace all occurrences of particular word in given a
file.
#!/bin/sh
#Write a script using sed command to replace all occurrences of
particular word in given a file.
cat sample.txt
echo -e "\n \t Applying sed command for finding lab and
replacing it with LAB: \n \t"
sed -i 's/LAB/laboratory/g' ggwp.txt
echo -e "\n \t After replacement new file is:"
cat ggwp.txt
Write a script using sed command to print duplicated lines in input
cat ggwp.txt
echo -e "\n Delete the Pattern mathing line"
sed -i '/SE/d' ggwp.txt
echo -e "\n Delete the Pattern mathing line"
sed -i 's/LAB/laboratory/g' ggwp.txt
echo -e "\n \t Duplicate Match TEXT:"
cat ggwp.txt
Conclusion:
The grep command is highly flexible with many useful operators and options. By combining
grep commands, you can get powerful results and find the text hiding in thousands of files. Sed
is a very powerful command in linux that allows you to update configuration files with ease.
With proper practice, you can efficiently manage multiple configuration files on the server very
fast.
EXPERIMENT 11
Problem Statement:
Write a shell script:
• Write an awk script to print all even numbers in a given range.
• Write an awk script to develop a Fibonacci series (take user input for number of terms).
• Write a perl script to sort elements of an array.
• Write a perl script to check a number is prime or not.
Theory:
AWK command in Unix/Linux with examples
Awk is a scripting language used for manipulating data and generating reports.The awk
command programming language requires no compiling, and allows the user to use variables,
numeric functions, string functions, and logical operators.
Awk is a utility that enables a programmer to write tiny but effective programs in the form of
statements that define text patterns that are to be searched for in each line of a document and the
action that is to be taken when a match is found within a line. Awk is mostly used for pattern
scanning and processing. It searches one or more files to see if they contain lines that matches
with the specified patterns and then performs the associated actions.
Awk is abbreviated from the names of the developers – Aho, Weinberger, and Kernighan.
WHAT CAN WE DO WITH AWK ?
1. AWK Operations:
(a) Scans a file line by line
(b) Splits each input line into fields
(c) Compares input line/fields to pattern
(d) Performs action(s) on matched lines.
2. Useful For:
(a) Transform data files
(b) Produce formatted reports
3. Programming Constructs:
(a) Format output lines
(b) Arithmetic and string operations
(c) Conditionals and loops
Perl
Perl is a programming language that can be used to perform tasks that would be difficult or
cumbersome on the command line. Perl is included by default with most GNU/Linux
distributions. Usually, one invokes Perl by using a text editor to write a file and then passing it to
the perl program.
Perl scripts can be named anything but conventionally end with ".pl". You can use any text editor
to create this file -- Emacs, Vim, Gedit, or whatever your favorite is. A script could look like
this: