You are on page 1of 53

Unix and Shell Programming Lab BTIT406

Practical - 01
Aim: Study of Unix Operating System & its architecture and perform installation of
Unix/Linux operating system.

The Unix operating system is a set of programs that act as a link between the computer and the user.
The computer programs that allocate the system resources and coordinate all the details of the computer's
internals is called the operating system or the kernel.
Users communicate with the kernel through a program known as the shell. The shell is a command line
interpreter; it translates commands entered by the user and converts them into a language that is understood by
the kernel.
• Unix was originally developed in 1969 by a group of AT&T employees Ken Thompson, Dennis Ritchie,
Douglas McIlroy, and Joe Ossanna at Bell Labs.
• There are various Unix variants available in the market. Solaris Unix, AIX, HP Unix and BSD are a few
examples. Linux is also a flavor of Unix which is freely available.
• Several people can use a Unix computer at the same time; hence Unix is called a multiuser system.
• A user can also run multiple programs at the same time; hence Unix is a multitasking environment.

Unix Architecture

Here is a basic block diagram of a Unix system −

The main concept that unites all the versions of Unix is the following four basics −
• Kernel − The kernel is the heart of the operating system. It interacts with the hardware and most of the
tasks like memory management, task scheduling and file management.

Rohit Verma 20100BTCSE07637 2nd/4th Page | 1


Unix and Shell Programming Lab BTIT406

• Shell − The shell is the utility that processes your requests. When you type in a command at your
terminal, the shell interprets the command and calls the program that you want. The shell uses standard
syntax for all commands. C Shell, Bourne Shell and Korn Shell are the most famous shells which are
available with most of the Unix variants. • Commands and Utilities − There are various commands and
utilities which you can make use of in your day to day activities. cp, mv, cat and grep, etc. are few
examples of commands and utilities. There are over 250 standard commands plus numerous others
provided through 3rd party software. All the commands come along with various options.
• Files and Directories − All the data of Unix is organized into files. All files are then organized into
directories. These directories are further organized into a tree-like structure called the filesystem.

Installation of Ubuntu/Linux
There are several ways to install Linux. You can clean everything from your system and install Linux. You can
dual boot Linux with Windows and choose one of the operating systems at the boot time. You can even install
Linux within Windows from Microsoft Store (though this only provides you with the command line version of
Linux).

But if you want to use Linux without making any changes to your Windows system, you can go the virtual
machine route. Basically, you install and use Linux like any regular Windows application. When you just want
to try Linux for limited use, virtual machines provide the most comfortable option.

Installing Linux inside Windows using VirtualBox

VirtualBox is free and open source virtualization software from Oracle. It enables you to install other operating
systems in virtual machines. It is recommended that your system should have at least 4GB of RAM to get
decent performance from the virtual operating system.

Requirements

• Good internet connection to download software and Linux ISO. (You can also use some other computer
with an internet connection to download these files.)
• Windows system with at least 12 GB of free space.
• Windows system with 4GB of rRAM. (It can work with less RAM as well, but your system will start to
lag while using Linux in the virtual machine.)
• Make sure to enable virtualization in the BIOS

Step 1: Download and install VirtualBox

Go to the website of Oracle VirtualBox and get the latest stable version from here:

https://www.virtualbox.org/

Installing VirtualBox is not rocket science. Just double-click on the downloaded .exe file and follow the
instructions on the screen. It is like installing any regular software on Windows.
Step 2: Download the Linux ISO

Rohit Verma 20100BTCSE07637 2nd/4th Page | 2


Unix and Shell Programming Lab BTIT406

Next, you need to download the ISO file of the Linux distribution. You can get this image from the official
website of the Linux distribution you are trying to use.

I am using Ubuntu in this example, and you can download ISO images for Ubuntu

https://ubuntu.com/download/desktop/thank-you?version=20.04.4&architecture=amd64

Step 3: Install Linux using VirtualBox

You have installed VirtualBox and you have downloaded the ISO for Linux. You are now set to install Linux in
VirtualBox.

Start VirtualBox, and click on the New symbol. Give the virtual OS a relevant name.

Allocate RAM to the virtual OS. My system has 8GB of RAM and I decided to allocate 2GB of it. You can use
more RAM if your system has enough extra.

Rohit Verma 20100BTCSE07637 2nd/4th Page | 3


Unix and Shell Programming Lab BTIT406

Create a virtual disk. This serves as the hard disk of the virtual Linux system. It is where the virtual system will
store its files.

I recommend using the VDI file type here.

Rohit Verma 20100BTCSE07637 2nd/4th Page | 4


Unix and Shell Programming Lab BTIT406

You can choose either the “Dynamically allocated” or the “Fixed size” option for creating the virtual hard disk.

The recommended size is 10 GB. However, I suggest giving it more space if possible. 15-20 GB is preferable.

Rohit Verma 20100BTCSE07637 2nd/4th Page | 5


Unix and Shell Programming Lab BTIT406

Once everything is in place, it’s time to boot that ISO and install Linux as a virtual operating system.

If VirtualBox doesn’t detect the Linux ISO, browse to its location by clicking the folder icon as shown in the
picture below:

Rohit Verma 20100BTCSE07637 2nd/4th Page | 6


Unix and Shell Programming Lab BTIT406

Soon you’ll find yourself inside Linux. You should be presented with the option to install it.

Things from here are Ubuntu-specific. Other Linux distributions may have slightly different looking steps, but it
won’t be complicated at all.

Rohit Verma 20100BTCSE07637 2nd/4th Page | 7


Unix and Shell Programming Lab BTIT406

You can skip to Continue.

Select ‘Erase disk and install Ubuntu’. Don’t worry. It won’t delete anything on your Windows operating
system. You are using the virtual disk space of 15-20GB that we created in previous steps. It won’t impact the
real operating system.

Just click on Continue.

Rohit Verma 20100BTCSE07637 2nd/4th Page | 8


Unix and Shell Programming Lab BTIT406

Things are pretty straightforward from here.

Self explanatory.

Rohit Verma 20100BTCSE07637 2nd/4th Page | 9


Unix and Shell Programming Lab BTIT406

Try to choose a password that you can remember. You can also reset the password in Ubuntu if you forget it.

You are almost done. It may take 10-15 minutes to complete the installation.

Rohit Verma 20100BTCSE07637 2nd/4th Page | 10


Unix and Shell Programming Lab BTIT406

Once the installation finishes, restart the virtual system.

If it gets stuck on the screen below, you may close the VirtualBox.

Rohit Verma 20100BTCSE07637 2nd/4th Page | 11


Unix and Shell Programming Lab BTIT406

Practical - 02
Aim: Study of UNIX general purpose utility commands.
1. mkdir :mkdir command stands for make directory. It is used to creates a new directory if a directory does
not already exists with the same name.
Syntax:
mkdir file_name

Options:
• -p: A flag which enables the command to create parent directories as necessary. If the directories exist,
no error is specified
• -v or –verbose: It displays a message for every directory created.
• -m: This option is used to set the file modes, i.e. permissions, etc. for the created directories. The syntax
of the mode is the same as the chmod command.
• –version: It displays the version number, some information regarding the license and exits.
• –help: It displays the help related information and exits.
Output:

2. ls :ls command stands for list. It is used to list all the files and directories
Syntax: ls and ls [options]

Options:

Rohit Verma 20100BTCSE07637 2nd/4th Page | 12


Unix and Shell Programming Lab BTIT406

• ls -a: list all files including hidden files. These are files that start with “.”. • ls -l: list the files in long
format i.e. with an index number, owner
• ls – o: list the files in long format but without the group name. • ls -g: list the files in long format but
without the owner Name.
• ls -i: list the files along with their index number.
• ls -s: list the files along with their size.
• ls -t: sort the list by time of modification, with the Newest at the top.
• ls -S: sort the list by size, with the largest at the top.
• ls -r: reverse the sorting order.
Output:

3. rmdir : rmdir command stands for remove directory. It is used to remove empty directories from the file
system

Syntax:
rmdir file_name or rmdir [options] file_name

Options:
• rmdir --help: It will print the general syntax of the command along with the various options that can be
used with the rmdir command as well as give a brief description about each option.

Rohit Verma 20100BTCSE07637 2nd/4th Page | 13


Unix and Shell Programming Lab BTIT406

• rmdir -p: In this option each of the directory argument is treated as a pathname of which all
components will be removed, if they are already empty, starting from the last component.
• rmdir --version: This option is used to display the version information
• rmdir -v, --verbose: This option displays verbose information for every directory being processed.

Output:

4. cd :cd command stands for change directory. It is used to change the current directory.

Syntax: cd directory_name

Options:
• cd: Returns you to your login directory
• cd - : Returns you to your previous working directory
• cd ~ : Also returns you to your login directory
• cd / : Takes you to the entire system’s root directory.
• cd /root : Takes you to the home directory of the root user. You must be the root user to access this
directory.
• cd /home : Takes you to the home directory, where user login directories are usually stored
Output:

Rohit Verma 20100BTCSE07637 2nd/4th Page | 14


Unix and Shell Programming Lab BTIT406

5. passwd: passwd command is used to change your login password. Syntax: passwd Output:

6. clear: This command is used to clear the terminal screen. Syntax: clear Output:

7. printf: “printf” command is used to display the given string, number or any other format specifier
on the terminal window. It works the same way as “printf” works languages like C. Syntax: printf
Output:

8. pwd: It is a command line utility for printing the current working directory. It will print the full
system path of the current working directory to standard output. Syntax: pwd Output:

9. cal: It is a calendar command in Linux which is used to see the calendar of a specific month or a
whole year.
Syntax: cal and cal [options]
Options:
• cal -y : Shows the calendar of the complete current year with the current date highlighted.
• cal 01 2002 : Shows calendar of selected month and year.
• cal 2024 : Shows the whole calendar of the year.

Rohit Verma 20100BTCSE07637 2nd/4th Page | 15


Unix and Shell Programming Lab BTIT406

• cal -3: Show 3-month output.


Output:

10. date: used to print current/system date and time in particular format Syntax: date

Options:
• date –R :output date/time in RFC 2822 format.

Rohit Verma 20100BTCSE07637 2nd/4th Page | 16


Unix and Shell Programming Lab BTIT406

• date –u :print or set coordinated universal time (UTC).


• –date or -d : Displays the given date string in the format of date. But this will not affect the system’s
actual date and time value. Rather it uses the date and time given in the form of string.
Output:

10. touch- It is used to create a file without any content. The file created using touch
command is empty.
This command can be used when the user doesn’t have data to store at the time of file creation.

Syntax: touch file_name

Options:
• touch -a: This command is used to change access time only. To change or update the last access or
modification times of a file touch -a command is used.
• touch -c : This command is used to check whether a file is created or not. If not created then don’t create
it. This command avoids creating files.
• touch -m : This is used to change the modification time only. It only updates last modification time.

Output:

12. echo: is used to print all the things written in single line to the console screen.
Syntax: echo Output:

Rohit Verma 20100BTCSE07637 2nd/4th Page | 17


Unix and Shell Programming Lab BTIT406

13. who: It is used to find time of last system boot, current run level of the system, list of logged in
users and more.
Syntax: who and who[option]

Options:
• who -H : is used to display the headings of the columns that were displayed in who command.
• who -m -H :Command to display the hostname and user associated with the input/output devices like a
keyboard.
• who -u : To display the whole list of logged-in users
• who -T -H :To display the status of the user’s message as -, + or?
• who -a :To display all details of currently logged in users.
Output:

14. uname: It is used to displays the information about the system.


Options:

• -a : It prints all the system information in the following order: Kernel name, network node hostname,
kernel release date, kernel version, machine hardware name, hardware platform, operating system
• -s : It prints the kernel name.
• -n : It prints the hostname of the network node(current computer).
• -r : It prints the kernel release date.
• -m : It prints the machine hardware name.
• -v : It prints the version of the current kernel.
• -p : It prints the type of the processor.
• -o : It prints the name of the operating system.
• -i : It prints the platform of the hardware.

Output:

Rohit Verma 20100BTCSE07637 2nd/4th Page | 18


Unix and Shell Programming Lab BTIT406

15. tty :There a command exists called tty which displays information related to terminal. The tty command
of terminal basically prints the file name of the terminal connected to standard input. Tty is short of
teletype, but popularly known as a terminal it allows you to interact with the system by passing on the
data (you input) to the system, and displaying the output produced by the system.
Syntax:
tty and tty[options] Options:
• -s, --silent, --quiet : Prints nothing, only returns an exit status.
• --help : It will display the help message and exit.
• --version : Prints the version information and exits.
Output:

16. stty : this command is used to change and print terminal line settings. Basically, this command shows or
changes terminal characteristics.

Syntax: stty and stty[options]

Rohit Verma 20100BTCSE07637 2nd/4th Page | 19


Unix and Shell Programming Lab BTIT406

Options:
• –all: This option print all current settings in human-readable form.
• -g: This option will print all current settings in a stty-readable form.
• --help : This option will display this help and exit.
• --version: This option will show the version information and exit.

Output:

Practical - 03
Aim: Study of execution of various file/directory handling commands.
File/directory handling commands:

Rohit Verma 20100BTCSE07637 2nd/4th Page | 20


Unix and Shell Programming Lab BTIT406

1. cat : This command is used to create file with entered content. It is also used to view the content of files.
Syntax: cat > newfile

Options:
• To view a single file Command: cat file_name
• To view a multiple file
Command: cat file_name1 file_name2....file_nameN
• -n : To display content with line numbers.
• -E : To display $ character at the end of each line.
• -T : To display ^I where tab space present in content.
Output:

2. cp: cp stands for copy. This command is used to copy files or group of files or directory. cp command
require at least two filenames in its arguments.

Syntax: cp [Option] source_file destination_file or


cp Src_file1 Src_file2 Src_file3 Dest_directory

Options:
• -i: i stands for Interactive copying. With this option system first warns the user before overwriting the
destination file. Cp prompts for a response, if you press y then it overwrites the file and with any other
option leave it uncopied.
• -b :With this option cp command creates the backup of the destination file in the same folder with the
different name and in different format. This will create a backup file with the tilde character(~)
appended to it.
• -r or -R :Copying directory structure. With this option cp command shows its recursive behaviour by
copying the entire directory structure recursively.

Output:

Rohit Verma 20100BTCSE07637 2nd/4th Page | 21


Unix and Shell Programming Lab BTIT406

3. mv: mv stands for move. Mv is used to move one or more files or directories from one place to another
in a file system.

Syntax: mv [Option] source destination

Options:
• -i: Like in cp, the -i option makes the command ask the user for confirmation before moving a file that
would overwrite an existing file, you have to press y for confirm moving, any other key leaves the file as
it is. This option doesn’t work if the file doesn’t exist, it simply rename it or move it to new location.
• -n: With -n option, mv prevent an existing file from being overwritten.
• -b: With this option, it is easier to take a backup of an existing file that will be overwritten as a result of
the mv command. This will create a backup file with the tilde character(~) appended to it.
• - -version: This option is used to display the version of mv which is currently running on your system.
Output:

4. rm: rm stands for remove here. Rm command is used to remove objects such as files, directories,
symbolic links and so on from the file system like UNIX.

Syntax: rm [OPTION]... FILE...


Options:

Rohit Verma 20100BTCSE07637 2nd/4th Page | 22


Unix and Shell Programming Lab BTIT406

• -i (Interactive Deletion): Like in cp, the -i option makes the command ask the user for confirmation
before removing each file, you have to press y for confirm deletion, any other key leaves the file
undeleted.
• -r: With -r(or -R) option rm command performs a tree-walk and will delete all the files and
subdirectories recursively of the parent directory. At each stage it deletes everything it finds.
Normally, rm wouldn’t delete the directories but when used with this option, it will delete.
• -f: rm prompts for confirmation removal if a file is write protected. The -f option overrides this minor
protection and removes the file forcefully.

Output:

5. wc: wc stands for word count. 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:
• -l :This option prints the number of lines present in a file. With this option wc command displays
twocolumnar output, 1st column shows number of lines present in a file and 2nd itself represent the file
name.
• -w :This option prints the number of words present in a file. With this option wc command displays
twocolumnar output, 1st column shows number of words present in a file and 2nd is the file name.
• -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.
• -m :Using -m option ‘wc’ command displays count of characters from a file.

Rohit Verma 20100BTCSE07637 2nd/4th Page | 23


Unix and Shell Programming Lab BTIT406

Output:

6. cmp: It is used to compare the two files byte by byte and helps you to find out whether the two files are
identical or not. When cmp is used for comparison between two files, it reports the location of the first
mismatch to the screen if difference is found and if no difference is found i.e. the files compared are
identical.cmp displays no message and simply returns the prompt if the files compared are identical.

Syntax:
cmp [OPTION]... FILE1 FILE2

Options:

• -l :This option makes the cmp command print byte position and byte value for all differing bytes. The
first column in the output represents the position (byte number) of differing bytes. The second column
represents the byte value of the differing byte in the first file, while the third column represents the byte
value of the differing byte in the second file.

• -s: This allows you to suppress the output normally produced by cmp command i.e it compares two files
without writing any messages. This gives an exit value of 0 if the files are identical, a value of 1 if
different, or a value of 2 if an error message occurs.

• -n: This option allows you to limit the number of bytes you want to compare, like if there is only need
to compare at most 25 or 50 bytes.

• -b(print-bytes): If you want cmp displays the differing bytes in the output when used with -b option.

Rohit Verma 20100BTCSE07637 2nd/4th Page | 24


Unix and Shell Programming Lab BTIT406

Output:

7. comm: The 'comm' command compares two files or streams. By default, 'comm' will always display
three columns. First column indicates non-matching items of first file, second column indicates
nonmatching items of second file, and third column indicates matching items of both the files. Both the
files has to be in sorted order for 'comm' command to be executed.

Syntax:
comm [OPTION]... FILE1 FILE2 Options:
• -1 :suppress first column(lines unique to first file).
• -2 :suppress second column(lines unique to second file).
• -3 :suppress third column(lines common to both files).
Suppress multiple columns:

• comm -23 (To display first column)


• comm -13 (To display second column)
• comm -12 (To display third column) Output:

Rohit Verma 20100BTCSE07637 2nd/4th Page | 25


Unix and Shell Programming Lab BTIT406

8. diff: diff stands for difference. This command is used to display the differences in the files by
comparing the files line by line. The important thing to remember is that diff uses certain special
symbols and instructions that are required to make two files identical. It tells you the instructions on how
to change the first file to make it match the second file. Special symbols are: a : add, c : change, d :
delete

Syntax: diff [options] File1 File2

Options:
• -c(context) : To view differences in context mode, use the -c option. The first file is indicated by ***, and
the second file is indicated by ---. The line with *************** is just a separator.
Output:

Rohit Verma 20100BTCSE07637 2nd/4th Page | 26


Unix and Shell Programming Lab BTIT406

Practical - 04
Aim: Study of file permission and ownership in UNIX OS.
File Access Mode: There are four file access mode:
1. Read: Grants the capability to read, i.e., view the contents of the file. Symbol: r
2. Write: Grants the capability to modify, or remove the content of the file. Symbol: w
3. Execute: User with execute permissions can run a file as a program. Symbol: x
4. Denied: User cannot read, write or execute the file. Symbol: -

File Owners: Every file and directory on your Unix/Linux system is assigned 3 types of owner, given below.

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. Symbol: u

Group: A user- group can contain multiple users. All users belonging to a group will have the same Unix group
permissions access 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. Symbol: g

Other: Any other user who has access to a file. This person has neither created the file, nor he belongs to a user
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. Symbol: o

• ls -l : This command is used to give list in long format. It gives the information of files/directory
permission ,types and many other information.

• Changing Permissions
To change the file or the directory permissions, use the chmod (change mode) command. There are two
ways to use chmod:- the symbolic mode and the absolute mode.
Syntax: chmod [file_owner][operator] [file_access_mode]
file_name

Symbolic Mode:

Rohit Verma 20100BTCSE07637 2nd/4th Page | 27


Unix and Shell Programming Lab BTIT406

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 Unix file permissions.

Operator Description

+ Adds a permission to a file or directory


– Removes the permission

= Sets the permission and overrides the permissions set earlier.

Output:

Number Permission Type Symbol

0 No Permission —

1 Execute --x

1. Give permission to user, group and other is rwx in cs2 file.


2. Take write permission to group in cs1 file using – operator.
3. Take read and write permission to user in f2 file using + operator.

Absolute (Numeric) Mode:


In this mode, file permissions are not represented as characters but a three-digit octal number. The table
below gives numbers for all for permissions types.

Rohit Verma 20100BTCSE07637 2nd/4th Page | 28


Unix and Shell Programming Lab BTIT406

Output:

2 Write -w-

4 Read r--

• Changing Owners and Groups


While creating an account on Unix, it assigns an owner ID and a group ID to each user. All the permissions
mentioned above are also assigned based on the Owner and the Groups.
Note: First we need to have administrator permission to add or delete groups. We can Login as root for this
purpose or using sudo.
In order to add a new group, we can use: sudo
addgroup
Two commands are available to change the owner and the group of files −
1. chown − The chown command stands for "change owner" and is used to change the owner of a file.
Syntax: chown [owner_name] file_name Options:
• -c: Reports when a file change is made.
• -f: It suppresses most of the error messages. When you are not permitted to change group permissions and
shows error, this option forcefully/silently changes the ownership.

Output:

Rohit Verma 20100BTCSE07637 2nd/4th Page | 29


Unix and Shell Programming Lab BTIT406

2. chgrp − The chgrp command stands for "change group" and is used to change the group of a file.
Syntax: chgrp [group_name] file_name

Options:
• -c or –changes: To describe the action for each File whose group actually changes.
• -f: To suppress error messages.

Output:

Rohit Verma 20100BTCSE07637 2nd/4th Page | 30


Unix and Shell Programming Lab BTIT406

Practical - 05
Aim: Study of vi editor: Creating and editing a text file with the vi-text editor using the standard vi editor
commands.
The vi editor is elaborated as visual editor. It is a very powerful application. An improved version of vi editor is
vim.
The vi editor has three modes:

• Command Mode: In command mode, actions are taken on the file. The vi editor starts in command mode.
Here, the typed words will act as commands in vi editor. To pass a command, you need to be in command
mode. In this mode, you can, move the cursor and cut, copy, paste the text. This mode also saves the changes
you have made to the file
• Insert Mode: In insert mode, entered text will be inserted into the file. The Esc key will take you to the
command mode from insert mode. You can switch to the Insert mode from the command mode by pressing
‘i’ on the keyboard
• Last Line Mode(Escape Mode): Line Mode is invoked by typing a colon [:], while vi is in Command
Mode. The cursor will jump to the last line of the screen and vi will wait for a command. This mode enables
you to perform tasks such as saving files, executing commands.

By default, the vi editor starts in command mode.


1. vi filename :- Creates a new file if it already does not exist, otherwise opens an existing file.

• Creating text file in vi editor Syntax: vi file_name Output:

• Editing/Inserting in vi editor
Here we insert the content in file. If you have to switch from command mode to insert mode press 'i' then
again switch to command mode press esc key.

There are many ways to enter insert mode from the command mode. i
: Inserts text before current cursor location.

Rohit Verma 20100BTCSE07637 2nd/4th Page | 31


Unix and Shell Programming Lab BTIT406

I : Inserts text at beginning of current line. a


: Inserts text after current cursor location.
A : Inserts text at end of current line.
o : Creates a new line for text entry below cursor location. O
: Creates a new line for text entry above cursor location.
r : Replace single character under the cursor with the next character typed.
R : Replaces text from the cursor to right.
r : Replaces single character under the cursor with any number of characters. S
:Replaces entire line.

Output:

Save and Exit Commands of the ex Mode : Need to press [Esc] key followed by the colon (:) typing
the following commands: q : Quit q! : Quit without saving changes i.e. discard changes. wq : Write
and quit (save and exit). w : Write to file called fileName (save as).
w! : Overwrite to file called fileName (save forcefully).

2. view filename: Opens an existing file in the read-only mode. Output:

Rohit Verma 20100BTCSE07637 2nd/4th Page | 32


Unix and Shell Programming Lab BTIT406

3. vi -R filename : Opens an existing file in the read-only mode.

Output:

Rohit Verma 20100BTCSE07637 2nd/4th Page | 33


Unix and Shell Programming Lab BTIT406

Practical – 06

Aim: Study of vi editor using C programming.


Steps -
1.Open terminal

Use the vim editor

Open file using,

2.vim file.c (file name can be anything but it should end with dot c extension) command.

To Edit the file:

3.Press i to go to insert mode.

Type your program.

4.To save the file:

Press Esc button and then type :wq. It will save the file.

To compile the program:

Type,

5.gcc file.c

To Run the program:

Type,

6. ./a.out

Output –

Rohit Verma 20100BTCSE07637 2nd/4th Page | 34


Unix and Shell Programming Lab BTIT406

6.1 Read input from user

6.2 Basic Calculator

Rohit Verma 20100BTCSE07637 2nd/4th Page | 35


Unix and Shell Programming Lab BTIT406

6.3 Using Control Statements

Rohit Verma 20100BTCSE07637 2nd/4th Page | 36


Unix and Shell Programming Lab BTIT406

6.4 Loop 1-10

6.5 Area of Circle

Rohit Verma 20100BTCSE07637 2nd/4th Page | 37


Unix and Shell Programming Lab BTIT406

Practical - 07
Aim: Study of shell programming & its types. Execute basic shell scripts.

Shell Scripting is an open-source computer program designed to be run by the Unix/Linux shell. Shell
Scripting is a program to write a series of commands for the shell to execute. It can combine lengthy and
repetitive sequences of commands into a single and simple script that can be stored and executed
anytime which, reduces programming efforts.

Types of Shell

Rohit Verma 20100BTCSE07637 2nd/4th Page | 38


Unix and Shell Programming Lab BTIT406

There are two main shells in Linux:

1. The Bourne Shell: The prompt for this shell is $ and its derivatives are listed below:

• POSIX shell also is known as sh

• Korn Shell also knew as sh

• Bourne Again SHell also knew as bash (most popular)

2. The C shell: The prompt for this shell is %, and its subcategories are:

• C shell also is known as csh

• Tops C shell also is known as tcsh

How to Write Shell Script in Linux/Unix


Shell Scripts are written using text editors. On your Linux system, open a text editor program, open a new
file to begin typing a shell script or shell programming, then give the shell permission to execute your
shell script and put your script at the location from where the shell can find it.

Let us understand the steps in creating a Shell Script:

1. Create a file using a vi editor (or any other editor). Name script file with extension .sh
2. Start the script with #! /bin/sh 3. Write some code.
4. Save the script file as filename.sh
5. For executing the script type bash filename.sh

“#!” is an operator called shebang which directs the script to the interpreter location. So, if we use”#! /bin/sh”
the script gets directed to the bourne-shell.

Program 1 – Basic Scripts

Rohit Verma 20100BTCSE07637 2nd/4th Page | 39


Unix and Shell Programming Lab BTIT406

Program 2 – Defining Variables

Program 3 - Read Only Variable

Program 4 – Command line Arguments

Rohit Verma 20100BTCSE07637 2nd/4th Page | 40


Unix and Shell Programming Lab BTIT406

Program 5 - Arithmetic Operations

Rohit Verma 20100BTCSE07637 2nd/4th Page | 41


Unix and Shell Programming Lab BTIT406

Practical - 08
Aim: Write the program for shell programming using decision statements like if then, if
then else, nested if, elif, case statements.

The following are the two types of decision-making statements we can use in Unix/Linux shell:

1. The if-else statement: If-else statements are useful to take a path from a given set of paths based on
the given conditions.

• if-fi: The if block is executed if the specified condition is true.


• if-else-fi: The if block is executed if the specified condition is true. Otherwise, the else block is
executed.
• if-elif-else-fi: The if block is executed if the condition specified in the if statement is true. Otherwise, the
next elif condition is checked. The elif block is executed if the condition specified in the elif statement is
true. The process goes on for the remaining elif statements until no condition is satisfied. If none of the
conditions of if or elif statements are satisfied, the else block is executed.
1. The case-sac statement: Case-sac statements are similar to switches. They are useful when all of the
different branches only depend on the value of a single input variable.

Program 1: Using if-fi condition

Rohit Verma 20100BTCSE07637 2nd/4th Page | 42


Unix and Shell Programming Lab BTIT406

Program 2: Using if else fi condition

Program 3: Using elif condition

Rohit Verma 20100BTCSE07637 2nd/4th Page | 43


Unix and Shell Programming Lab BTIT406

Program 4: Using logical operator

Program 5: Using Switch case

Rohit Verma 20100BTCSE07637 2nd/4th Page | 44


Unix and Shell Programming Lab BTIT406

Practical - 09

Aim: Write the program for shell programming using loops.

If we want to perform an operation multiple times with a single variable change or based on a

condition then we need to write the logic number of times. So, instead of that, we can use loops to

perform an operation a certain number of times. In shell scripting, different types of loops are available

to perform looping such as for loop, while loop, and until loop. These loops will execute commands

iteratively until a condition satisfies and comes out of the loop when the condition is not satisfied. We

can control the loops using some keywords in shell scripting and we can use loops to automate

repetitive tasks.

Types of Loops in Shell Scripting

Below are the 3 different types of loops in shell scripting which are as follows:

1. While Loop
The while loop syntax in the shell scripting will be represented in the following way.

Rohit Verma 20100BTCSE07637 2nd/4th Page | 45


Unix and Shell Programming Lab BTIT406

Syntax:

while [ condition ] do

command1

command2

done

In the above syntax, initially, the condition will be evaluated if it is true then the commands inside the

loop will execute until the condition remains true else it will come outside of the loop. Here while, do,

and done are built-in keywords. It will execute all the commands while the condition evaluates to true.

2. For Loop
For loop is another type of looping statement to execute a set of commands for a certain number of

times. Let’s have a look at the syntax of for loop in shell scripting and it can be represented as below:

Rohit Verma 20100BTCSE07637 2nd/4th Page | 46


Unix and Shell Programming Lab BTIT406

syntax:

for var in list

do

command 1

command 2

In the above for loop syntax, the list is a list of values or characters and var will have the values from the list

one by one for each iteration and list of commands in the body of the loop will execute. Once the entire list is

do done then it will come out of the loop. In the above for loop syntax, for, do, and done are built-in
ne keywords. Now we will understand for loop with an example in detail

3. Until Loop
Until loop is one of the looping statements in the shell scripting and this looping statement is similar to

the while loop statement which we have discussed earlier. The difference between two is, it will

Rohit Verma 20100BTCSE07637 2nd/4th Page | 47


Unix and Shell Programming Lab BTIT406

execute the body of the loop until the conditional statement becomes true whereas while loop executes

commands if the condition is true. Let us have a look at the syntax of until loop in the shell scripting

as below:

Syntax:

until [ conditional statement ] do

command1

command2

done

In the above until loop syntax, until, do, and done are built-in keywords of the shell scripting. This

loop will do the same task as other loops are doing and it is almost similar to the while loop but in such

situations, we need to use only until loop as it will be a better way to do that task rather than doing

with while loop. Let us say leave the clothes on the stand until they are dry or leave the clothes on the

stand while they are dry. Both sentences are correct but the first sentence seems to be more appropriate

like that we need to choose until than while loop in a few

Rohit Verma 20100BTCSE07637 2nd/4th Page | 48


Unix and Shell Programming Lab BTIT406

Practical – 10

Aim: Study of execution of various system administrative commands.


A system administrator manages configuration, upkeep and reliable operations of computer operations.
Sysadmin handles servers, has to manage system performance and security without exceeding the
budget to meet users need.

A system administrator only deals with terminal interface and hence it is very important to learn and
become master in commands to operate from terminal. Some important commands for system
administrators
Command Function
man Display information about all commands
uptime Show how long system is running
users Show username who are currently logged in
service Call and execute script
pkill Kill a process
pmap Memory map of a process
wget Download file from network
ftp or sftp Connect remote ftp host
free Show memory status
top Display processor activity of system
last Display user's activity in the system
ps Display about processes running on the system
Shutdown commands Shutdown and reboot system
info Display information about given command
env Display environment variable for currently logged-in user
netstat Display network status
arp Check ethernet connectivity and IP address
df Display filesystem information
du Display usage

Rohit Verma 20100BTCSE07637 2nd/4th Page | 49


Unix and Shell Programming Lab BTIT406

init Allow to change server bootup


nano A command line editor
nslookup Check domain name and IP information
shred Delete a file by over writing its content
cat Display, copy or combine text files
pwd> Print path of current working directory
locate Finding files by name on system
chown Change ownership of a file
>alias To short a command
echo Display text
cmp Compare two files byte by byte
mount Mount a filesystem
ifconfig Display configuration
traceroute> Trace existing network
sudo Run a command as a root user
route List routing table for your server
ping Check connection by sending packet test packet
find Find location of files/directories
users Show current logged in user
who Same as w but doesn't show current process
ls List all the files
tar Compress directories
grep Search for a string in a file
su Switch from one to another user
awk Search lines for a given pattern

1. Uptime Command

In Linux uptime command shows how long your system is running and the number of users who are currently
logged in and also displays the load average of a system for 1, 5, and 15 minutes intervals.

2. Top Command

Top command displays processor activity of your system and also displays tasks managed by kernel in real-
time. It’ll show processor and memory are being used.
Using the top command with u the option will display specific User process details as shown below. Press
‘O‘ (uppercase letter) to sort as desired by you. Press ‘q‘ to quit from the top screen.

Rohit Verma 20100BTCSE07637 2nd/4th Page | 50


Unix and Shell Programming Lab BTIT406

3.Free command

The free command shows free, total, and swap memory information in bytes.

4. Last command

With the last command, we can watch the user’s activity in the system. This command can execute normal
users also. It will display complete user’s info like terminal, time, date, system reboot or boot, and kernel
version. A useful command to troubleshoot.

Rohit Verma 20100BTCSE07637 2nd/4th Page | 51


Unix and Shell Programming Lab BTIT406

5.Systemctl Command

Systemctl command is a systemd management tool that is used to manage services, check running
statuses, start and enable services and work with the configuration files.

Rohit Verma 20100BTCSE07637 2nd/4th Page | 52


Unix and Shell Programming Lab BTIT406

Rohit Verma 20100BTCSE07637 2nd/4th Page | 53

You might also like