Linux Manual
Linux Manual
VISION
To be a premier institute of knowledge of share quality research and development technologies towards
national buildings
MISSION
• Develop the state of the art environment of high quality of learning
• Collaborate with industries and academic towards training research innovation and entrepreneurship
• Create a platform of active participation co-circular and extra-circular activities
MISSION
• To impart high standard value-based technical education in all aspects of Computer Science
and Engineering through the state of the art infrastructure and innovative approach.
• To produce ethical, motivated, and skilled engineers through theoretical knowledge and
practical applications.
• To impart the ability for tackling simple to complex problems individually as well as in a team.
• To develop globally competent engineers with strong foundations, capable of “out of the box”
thinking so as to adapt to the rapidly changing scenarios requiring socially conscious green
computing solutions.
PEO1: Strong foundation of knowledge and skills in the field of Computer Science and Engineering.
PEO2: Provide solutions to challenging problems in their profession by applying computer engineering
theory and practices.
PEO3: Produce leadership and are effective in multidisciplinary environment.
COURSE OBJECTIVES
• To understand LINUX operating system and its internals.
• To understand LINUX file system structure and its operations.
• To understand LINUX shell environment and its programming.
• To understand communication in LINUX and the corresponding primitives.
COURSE OUTCOMES(CO)
• The student learns about LINUX features for multiuser, multitasking capabilities.
• The student learns about file system organization, file and directory manipulation, setting file
permissions, and disk free space administration.
• The student learns about writing shell scripts for different applications.
• The student learns about how users communicate with each other in LINUX environment.
1. Students are advised to come to the laboratory at least 5 minutes before (to the starting time), those who
come after 5 minutes will not be allowed into the lab.
2. Plan yourtask properly much before to the commencement, come prepared to the lab with the synopsis /
program / experiment details.
3. Studentshouldenterintothelaboratorywith:
a. Laboratory observation notes with all the details (Problem statement, Aim, Algorithm, Procedure,
Program, Expected Output, etc.,) filled in for the lab session.
b. Laboratory Record updated up to the last session experiments and other utensils (if any) needed in the lab.
c. ProperDresscodeandIdentitycard.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system allotted to you
by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab observation note book, and
get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must maintain the discipline
and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded systems, which should be utilized
properly.
8. Students/Facultymust keeptheir mobilephonesinSWITCHEDOFFmodeduringthe lab sessions. Misuse of
the equipment, misbehaviors with the staff and systems etc., will attract severe punishment.
9. Students must take the permission of the faculty in case ofany urgency to go out; if anybody found loitering
outside the lab / class without permission during working hours will be treated seriously and punished
appropriately.
10. Students should LOG OFF/ SHUT DOWN the computer systembefore he/she leaves the labafter
completing the task(experiment) inallaspects. He/she must ensure the system/ seat is kept properly
EXPERIMENTS
1) Study and practice on file system / handling files with commands, syntax, usage,
application.
2) Practice on vi editor.
3) Study and practice on redirection operators with relevant commands, syntax, usage,
application.
4) Study and practice on filters with relevant commands, syntax, usage, application.
5) Study and practice on Backup with relevant commands, syntax, usage, application.
6) Study and practice on internet related commands, syntax, usage, application.
7) Study and practice on shells/shell programming with relevant programming constructs,
syntax, usage, application.
8) Study and practice on awk with relevant commands, syntax, usage, application.
9) Study and practice on regular expressions and the grep family with relevant commands,
syntax, usage, application.
10) Study and practice on compilation process of C programs under UNIX.
References:
1. Unix concepts and applications by Sumitabha Das, TMH Publications.
2. Shell programming by Yashwanth Kanetkar.
TABLEOF CONTENTS
1 Study and practice on file system / handling files with commands, 4-7
syntax, usage, application
2 Practice on vi editor. 8-12
3 Study and practice on redirection operators with relevant commands, 13-14
syntax, usage, application.
4 Study and practice on filters with relevant commands, syntax, usage, 15-20
application.
5 Study and practice on Backup with relevant commands, syntax, usage, 21-22
application.
6 Study and practice on internet related commands, syntax, usage, 23-25
application.
7 Study and practice on shells/shell programming with relevant 26-36
programming constructs, syntax, usage, application.
8 Study and practice on awk with relevant commands, syntax, usage, 37-38
application.
9 Study and practice on regular expressions and the grep family with 39-40
relevant commands, syntax, usage, application.
10 Study and practice on compilation process of C programs under UNIX. 41-43
Viva-Voce Questions 44-54
Sanketika Vidya Parishad Engineering College
INTRODUCTIN TO LINUX
Linux is an open-source operating system. It is like Windows, Mac, Android, etc. Unix is
also an operating system like Linux. It is a commercial OS. It consists of three parts:
Kernal, Shell, and Programs. Most of the Unix and Linux commands are similar in nature.
Linux is an open- source Unix- like operating system-based family on the Linux kernel, and
the OS kernel was first published on 17th September 1991 by LinusTorvalds.
KernelMode vs UserMode
Kernel component code executes in a special privileged mode called kernel mode with
full access to all resources of the computer. This code represents a single process,executes
in a single address space, and does not require any context switch hence is very efficient
and fast. The kernel runs each process and provides system services to processes,
providing protected access to hardware to processes.
1
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
Support code that is not required to run in kernel mode is in System Library. User
programs and other system programs work in User Mode which has no access to the
system hardware and kernel code. User programs/ utilities use System libraries to access
Kernel functions to get the system's low-level tasks.
BasicFeatures
Following are some of the important features of the Linux OperatingSystem.
• Portable − Portability means software can work on different types of hardware in
the same way. Linux kernel and application programs support their installation on
any kind of hardware platform.
• Open Source−Linux source code is freely available and it is a community-based
development project. Multiple teams work in collaboration to enhance the
capability of the Linux operating system and it is continuously evolving.
• Multi-User − Linux is a multi user system means multiple users can access system
resources like memory/ram/application programs at the same time.
• Multiprogramming − Linux is a multiprogramming system that means multiple
applications can run at thesametime.
• Hierarchical File System − Linux provides a standard file structure in which
system files/ user files arearranged.
• Shell − Linux provides a special interpreter program that can be used to execute
commands of the operatingsystem. It can be used to do various types of operations,
call application programs. etc.
• Security−Linux provides user security using authentication features like password
protection/controlled access to specific files/encryption of data.
Architecture
The following illustration shows the architecture of a Linux system−
2
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
3
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
Ex-1: Study and practice file system/handling files with commands, syntax, usage, and
application.
A file system is a method or structure used by an operating system to organize and store data
on storage devices, such as hard drives, solid-state drives, or optical discs. It provides a logical
and efficient way to manage files, directories, and their associated metadata.
In Linux, most of the operations are performed on files. And to handle these files Linux
has directories also known as folders which are maintained in a tree-like structure. Though,
these directories are also a type of file themselves. Linux has 3 types of files:
Regular Files: It is the common file type in Linux. it includes files like – text files, images,
binary files, etc. Such files can be created using the touch command. They consist of the
majority of files in the Linux/UNIX system. The regular file contains ASCII or Human
Readable text, executable program binaries, program data and much more.
Directories: Windows call these directories as folders. These are the files that store the list of
file names and the related information. The root directory(/) is the base of the system, /home/
is the default location for user’s home directories, /bin for Essential User Binaries, /boot –
Static Boot Files, etc. We could create new directories with mkdir command.
Special Files: Represents a real physical device such as a printer which is used for IO
operations. Device or special files are used for device Input/Output(I/O) on UNIX and Linux
systems. You can see them in a file system like an ordinary directory or file.
2. MkdirCommand
The mkdir command is used to create a new directory under any directory.
Syntax:
mkdir
<directory
name>
4
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
Output:
3. rmdirCommand
The rmdir command is used to delete a directory.
Syntax:
rmdir
<directory
name>
Output:
4. ls
Command
The ls command is used to display a list of content of a directory.
Syntax:
ls
Output:
5. cdCommand
The cd command is used to change the current directory.
Syntax:
cd
<directory
name>
Output:
2.LinuxFilecommands
6. touchCommand
The touch command is used to create empty files. We can create multiple empty files by
5
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
executing it once.
Syntax:
touch<file name>
touch<file1><file2>....
Output:
7. catCommand
The cat command is a multi-purpose utility in the Linux system.It can be used to create
a file, display content of the file, copy the content of one file to another file, and more.
Syntax:
cat[OPTION]...[FILE]..
To create a file, execute it as follows:
cat ><filename>
//Enterfilecontent
Press "CTRL+ D" keys to save the file. To display the content of the
file, execute it as follows:cat<file name>
Output:
8. rmCommand
The rm command is used to remove a file.
Syntax:
rm<filename>
Output:
9. cpCommand
The cp command is used to copy a file or directory.
Syntax:
Tocopyinthesame directory:
cp <existing file
6
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
name><new file name>
Output:
10. mvCommand
The mv command is used to move a file or a directory form one location to another
location.
Syntax:
mv <file
name><directory
path>
Output:
7
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
Ex-2:Practiceonvieditor.
WhatistheVIeditor?
The VI editor is the most popular and classic text editor in the Linux family. Below, are
some reasons which make it a widely used editor–
1) It is available in almost all Linux Distributions
2) It works the same across different platforms and Distributions
3) It is user-friendly. Hence, millions of Linux users love it and use it for their editing needs
Nowadays, there are advanced versions of the vi editor available, and the most popular
one is VIM which is Vi Improved. Some of the other ones are Elvis, Nvi, Nano, and Vile.
It is wise to learn vi because it is feature-rich and offers end less possibilities to edit a file.
To work on VI editor, you need to understand its operation modes. They can be
divided into two main parts.
vi Command mode:
• The vi editor opens in this mode, and it only understands commands
• 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
8
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
can create a new file.
9
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
VIEditingcommands
• i–Insert at cursor(goesintoinsert mode)
10
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
• a–Writeaftercursor(goesintoinsertmode)
• A– Writeattheendofline(goesintoinsertmode)
• ESC–Terminateinsertmode
• u –Undo last change
• U–Undo all changes to the entire line
• o–Open a new line (goes into insert mode)
• dd–Delete line
• 3dd–Delete 3lines.
• D– Delete contents of line after the cursor
• C–Delete contents of a line after the cursor and insert newtext. Press ESC key to end
insertion.
• dw–Delete word
• 4dw– Delete4 words
• cw–Change word
• x –Delete character at the cursor
• r–Replace character
• R–Overwrite characters from cursor onward
• s –Substitute one character under cursor continue to insert
• S–Substitute entire line and begin to insert at the beginning of the line
• ~ – Change case of individual character
Note: You should be in the “command mode” to execute the se commands. VI editor is
case-sensitive so make sure you type the commands in the right letter-case.
Make sure you press the right command otherwise you will end up making undesirable
changes to the file. You can also enter the insertmode by pressing a, A , o , as required.
Moving with in a file
• k–Move cursor up
You need to be in the command mode to move with in a file. The default keys for
navigation are mentioned below else; You can also use the arrow keys on the
keyboard.
11
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
Saving and Closing the file
• Shift+zz–Save the file and quit
12
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
Ex-3: Study and practice on redirection operators with relevant commands,
syntax, usage andapplication.
Linux I/O Redirection
Redirection can be defined as changing the way from where commands read input to
where commands sends output. You can redirect input and output of acommand.
For redirection, meta characters are used.Redirection can be into a file (shell meta
characters are angle brackets'<','>') or a program( shell meta characters are pipe
symbol'|').
Standard Streams In I/O Redirection
The bash shell has three standard streams in I/O redirection:
o standardinput(stdin):The stdinstream is numbered as stdin(0).The bash shell
takes input from stdin. By default, keyboard is used as input.
o standardoutput(stdout):The stdout stream is numbered as stdout(1).The bash
shell sends output to stdout. Output goes to display.
o standarderror(stderr):The stderr stream is numbered as stderr(2).The bash shell
sends error message to stderr .Error message goes to display.
1. LinuxInputRedirection
<stdin
The bash shell uses stdin to take input. In input redirection, a file is made in put to the
command and this redirection is done with the help of '<'sign.
Syntax:
cat<<file
Name>
Exampl:
cat<file.txt
Look at the above snapshot, command "cat<file.txt" has taken 'file.txt' as input and display
edits content.
13
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
2. LinuxOutputRedirection
Output redirection is used to put output of one command into a file or into another
command.
> stdout
The stdout is redirected with a '>' greaterthan sign.When shell meets the '>' sign, it will
clear the file (as you already know).
Example:
Echo Hello everyone. > afile.txt
Look at the above snapshot, greater than sign'>'redirects the command 'echo' output into a
file 'afile.txt'.
3. Linux ErrorRedirection
2>stderr
Command '2>' redirects the error of an output.It helps us you to keep our display less messy
by redirecting error messages.
Example:
zchohyii2>/dev/null
Look at the above snapshot, by using command "zcho hyii2>/dev/null" (here echo
command is wrong), we didn't get any error message. But when we use command "zcho
hyii" error message is displayed in the terminal. Hence, '2>' redirects the error message
in the mentioned directory keeping your terminal error message free.
14
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
Ex-4:Study and practice on filters with relevant commands, syntax, usage and
applications.
Linux Filters
Linux Filter commands accept input data from stdin (standard input) and produce
output on stdout (standard output).It transforms plain-text data into a meaningful way
and can be used with pipes to perform higher operations.
These filters are very small programs that are designed for a specific function which can be
used as building blocks.
Linux Filter Commands
1. cat
2. grep
3. sort
4. Number sorting
5. Head
6. tail
7. Tac
8. uniq
9. wc
10. sed
1. LinuxCatFilters
When cat command is used inside pipes, it does nothing except moving stdin to stout.
Syntax:
cat <fileName> | cat or tac |cat
or tac |. . .Example:
catweeks.txt|tac|cat|cat|tac
15
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
Look at the above snapshot, output of one 'cat' or 'tac' command is passing on to another as
input.
2. Grep Command in Linux/Unix
The 'grep' command stands for "global regular expression print". Grep command filters
the content of a file which make sourse arch easy.
Syntax:
grep<searchWord>
<filename>
Example: grep 9
marks.txt
Look at the above snapshot, grep command do the same work as earlier example but
without pipe.
Grep options
O grep-v M:The 'grep-v' command displays lines not matching to the specified word.
Syntax:
grep -v <searchWord>
<fileName>
Example:
grep-v 9 marks.txt
Look at the above snapshot, command "grep-I red exm.txt" displays all lines
containing 'red' whether in uppercase or lowercase.
3. Linux sort
The 'sort' command sorts the file content in alphabetical order.
Syntax:
sort <fileName>
Example:
sortweeks.txt
Look at the above snapshot, the 'sort' command has sorted the file 'weeks.txt' in alphabetical
order.
4. Numeric Sorting
Numeric sorting is different from alphabetical sorting. For numeric sorting option 'n' is
17
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
used along with the column number if required.
Syntax:
sort -n -
k<columnNumber>
<fileName>Example:
sort-n-k2marks.txt
5. headCommand
The head command is used to display the content of a file. It displays the first 10 lines of a
file.
Syntax:
head
<file
name>
Output:
6. Tail Command
The tail command is similar to the head command. The difference between both
commands is that it displays the last ten lines of the file content. It is useful for reading
the error message.
Syntax:
18
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
tail
<file
name
Output
7.tacCommand
The tac command is the reverse of cat command, as its name specified. It displays the
file content in reverse order (from the lastline).
Syntax:
tac
<file
name
Output:
8. uniq Command
The uniq command is used to form a sortedlist in which every word will occur only once.
Syntax:
command<fileName>|uniq
19
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
Output:
9.wc Command
The wc command is used to count the lines, words, and characters in a file.
Syntax:
wc
<file
name
Output
10.sed command
The sed command is also known as streameditor. It is used to edit files using a regular
expression. It does not permanently edit files; instead, the edited content remains only on
display. It does not affect the actual file.
Syntax:
command|sed's/<oldWord>/<newWord>/'
Output:
20
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
21
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
SYNTAX :
Create a new archive named "archive.tar" from a file called "file1.txt" and a directory called
"my_directory":
$ tar -cvf archive.tar file1.txt my_directory
Extract files from the "archive.tar":
$ tar -xvf archive.tar
Create a gzipped archive named "archive.tar.gz" from a directory "my_files":
$ tar -czvf archive.tar.gz my_files
Extract files from a gzipped archive "archive.tar.gz":
$ tar -xzvf archive.tar.gz
Remember, the order of options is essential. For example, when creating an archive, -cvf
must be used together, where -c specifies the "create" mode, -v enables verbose mode, and -f
indicates the filename to be used. Similarly, when extracting, use -xvf together to indicate
"extract," enable verbose mode, and specify the filename.
You can check the manual page for tar for more details and additional options by tar in
your terminal.
22
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
finger command:
The finger command in Linux is used to display information about users on a Unix-
like operating system. It provides details about users who are currently logged into the
system or information about a specific user. However, please note that the usage of the finger
command might vary depending on the Linux distribution and the system's configuration.
The basic syntax of the finger command is as follows:
finger [username]
If you run the command without specifying a username, it will display information about all
users who are currently logged in. If you provide a username as an argument, it will show
detailed information about that specific user.
Here is an example of using the finger command:
finger
This command might output something like:
Login Name Tty Idle Login Time Office Office Phone
user1 John Doe tty1 4:25 Aug 9 10:00 (:0)
user2 Jane Smith pts/0 Aug 9 11:30 (192.168.1.2)
user3 Alice Johnson pts/1 1:23 Aug 9 12:15 (192.168.1.3)
In this example, you can see the logged-in users' login names, real names, terminal types
(e.g., tty1 or pts/0 for pseudo-terminals), idle times, and login times.
NOTE:- the finger command might not be available on all Linux distributions by default,
and its usage might be restricted for security reasons.
rlogin command:
The rlogin command in Linux is used to establish a remote login session between your
local machine and a remote machine. It allows you to log in to the remote machine and work
as if you were sitting directly in front of it. However, as I mentioned before, rlogin is
considered insecure due to the way it transmits data, and it's recommended to use more
secure alternatives.
You can use the rlogin command to establish a remote login session on another system. The
syntax for the rlogin command is:
23
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
$ rlogin hostname or ip address
The following example shows you how to log in remotely to the host2 system as another
user, user2:
$ rlogin -l user2 host2
Password:
Last login: Mon Mar 6 16:36:35 from host2
Sun Microsystems Inc. SunOS 5.9 Generic February 2000
... (output truncated)
$ pwd
/export/home/user2
$ uname -n
host2
$ exit
Connection to host2 closed.
For getting ip address : If you enter the command “ifconfig” in the terminal, all information
will be displayed. You can also use the commands “ip addr” or “ip a”. Confirm with [Enter]
Telnet command:-
Telnet :- Telnet is an old network protocol that is used to connect to remote systems over a
TCP/IP network. It connects to servers and network equipment over port 23. Let’s take a
look at Telnet command usage.
In Linux, the telnet command is used to establish a simple text-based communication
with another device or server over the Telnet protocol. However, it's important to note that
Telnet is generally considered insecure because it transmits data, including passwords, in
plain text.
Syntax:-telnet [options] [host [port]]
options: These are optional command-line options you can use with the telnet command.
host: This is the hostname or IP address of the device you want to connect to.
port: This is the port number to connect to. The default Telnet port is 23.
For example, if you want to connect to a Telnet server with the IP address "192.168.1.100"
on port 23, you would use the following command:
$ Telnet 192.168.1.100 23
To exit the telnet command, execute the logout command.
$ logout
ftp command:-
FTP:- FTP (File Transfer Protocol) is a network protocol used for transferring files from one
computer system to another. Even though the safety of FTP tends to spark a lot of discussion,
it is still an effective method of transferring files within a secure network.
In Linux, the ftp command is used to interact with remote servers using the FTP (File
Transfer Protocol) for transferring files between your local machine and the remote server.
Syntax:-telnet [options] [host [port]]
For example, if you want to connect to an FTP server with the hostname "ftp.example.com",
you would use the following command:
24
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
$ ftp ftp.example.com
After connecting, you can start using FTP commands to interact with the remote server.
To exit the FTP command, execute the logout command.
$ logout
Apr command :-
The Address Resolution Protocol (ARP) command is used to map IP addresses to
MAC addresses on a local network. The ARP command allows you to manage and
manipulate ARP cache entries on a Linux system. The ARP cache is a table that stores the
IP-to-MAC address mappings for devices on the same network segment.
What is MAC network address?
A MAC (Media Access Control) address, sometimes referred to as a hardware or physical
address, is a unique, 12-character alphanumeric attribute that is used to identify individual
electronic devices on a network. An example of a MAC address is: 00-B0-D0-63-C2-26.
What is IP address?
An Internet Protocol (IP) address is a unique numerical identifier for every device or network
that connects to the internet. Typically assigned by an internet service provider (ISP), an IP
address is an online device address used for communicating across the internet
The basic syntax of the ARP command in Linux is:
$ arp [options] [hostname]
Display ARP Cache: To view the current ARP cache entries, you can simply run the arp
command without any options:
$ arp
Add Static ARP Entry: You can manually add a static ARP entry to the cache using the -s
option:
$ sudo arp -s <IP_address><MAC_address>
For example:
$ sudo arp -s 192.168.1.100 00:11:22:33:44:55
Delete ARP Entry: To remove an ARP cache entry, use the -d option:
$ sudo arp -d <IP_address>
For example:
$ sudo arp -d 192.168.1.100
Flush ARP Cache: You can flush the entire ARP cache using the -a option:
$ sudo arp -a -d
25
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
EX 7:- Study and practice on shells /shell programming with relevant programming
constructs, syntax, usage and applications.
Whatisashell?
A shell in Linux is a command-line interface that allows users to interact with the operating
system by typing text commands. It serves as an intermediary between the user and the OS,
executing commands and displaying their results. Popular Linux shells include Bash, which is
the default on many distributions. Users can navigate the file system, launch programs, manage
files, and automate tasks through shell scripting. Shell scripting allows users to create scripts
to execute sequences of commands efficiently.
Types of shell :
Bash (Bourne Again SHell): Bash is the default shell for many Linux distributions. It is a
powerful and versatile shell that provides a wide range of features, including command-line
editing, history, tab completion, and scripting capabilities. It is based on the original Unix sh
(Bourne Shell) but with additional improvements.
sh (Bourne Shell): The original Unix shell that served as the foundation for many modern
shells. It is a simple shell with limited features compared to more recent shells like Bash.
zsh (Z Shell): Zsh is an extended version of Bash with additional features and
improvements, such as better auto-completion, spelling correction, and more customization
options.
csh (C Shell): The C Shell is another Unix shell that provides a syntax similar to the C
programming language. It offers interactive features like history and command-line editing.
tcsh (TENEX C Shell): An enhanced version of csh, offering improvements like better
command-line editing and command-line completion.
ksh (Korn Shell): The Korn Shell is another powerful shell with advanced scripting
capabilities and improved interactive features.
Whatisshellscripting?
Shell scripting is the process of writing and executing small programs (scripts) in a shell
(e.g., Bash) to automate tasks, execute commands, and control the operating system. Scripts
can combine multiple commands, use variables, and include control structures like loops and
conditionals for decision-making. Shell scripting is commonly used for automation, file
management, text processing, and system configuration on Unix-like operating systems like
Linux.
Creating a shell program
1.Using‘gedit’
26
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
One method of creating a “.sh” file is by using the edit command. You can directly create
and open a “.sh”filebyspecifying thenameofthefileasshownbelow,oryou
cansimplyusetheeditcommandand savethefile andnameitlater.
Youmustbecarefulwhilenamingyourfilebecauseifyouwritethenameofanalreadyexistingfilewit
hthe command,itwillopentheexistingfileinsteadofcreatingone.
2.Usingnanoeditor
Another method to create a “.sh” file is by using the nano editor in Linux-based operating
systems. It workssimilar to the gedit command where you specify the name of the file you
want to create next to the command
Similar to the gedit command, even the nano command will open the existing file
instead of creating a newoneifyouenterthe nameofanalreadyexistingfile.
1.UsingVieditor
We all know that the Vi editor is a really powerful editor for text manipulation, but not that
easy for textcreation,meaning it will be even harder to write shellprograms in it.None the
less, to create a “.sh” file using the ‘vi’command,specify the name of the file after the Vi
command as shown below:
Even the Vi editor will open the existing file if you enter the name of an already existing file.
PRINTING“HELLOWORLD”
To do so, write the following piece of code in your “.sh”file:
The above code includes just 2 lines (although it is technically one), the first line must be
written in all the shell programs, it simply specifies the shell we are using, in this case, it is
the bashshell.
OK, now that we have written and saved our code, how do we execute it? Well, we simply
type the command sh followed by the name of the file you save it in as follows:
27
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
sh<filename>.sh
We just printed“Hello ”
The shell program above will print out the following output:
28
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
You can even print some text before the number to give a better understanding of the output
as shown:
We can create many variables like float, integers, strings and so many more in a similar
fashion.
READING INPUT FROM THE USER
We can read the input from the user by using the keyword “read” followed by the variable
you want to assign it to. For example the statement “read x” will read the user’s input and
store it in the variable “x”.
The shell program shown above will read the number entered by the user into the variable x
and then print it out as shown:
And upon running the above code, we get the following output:
When we are using expressions, we obviously have some operators to operate on. Operators
are of 3 types, arithmetic and relational, and logical, let us look at each of them:
The arithmetic operators are:
1. Addition(+)
2. Subtraction(-)
3. Division(/)
4. Multiplication(\*)
30
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
As you can see everything is in traditional style except for the multiplication operator, let us
look at one example of it to clarify:
The shell program shown above will print the following output:
<arguments>Fi
31
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
output:
2.“if…then…else”statement
If <condition>Then
<arguments>Else
<arguments>Fi
32
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
2. “if…then…elseif…then…else”statement
If <condition>Then
<arguments>Elseif <condition>Then
<arguments>Else
<arguments>Fi
Upon executing the program shown above, we get the following output:
3. Nested if
We can also nest one if loop in side another if loop,to further narrow own the condition, the
following is a really beautiful example that illustrated if loops using all of the information we
33
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
learned till now like environment variables, logical operators, nestedif, else, comments and
more:
Upon executing the program shown above, we get the following output:
and exits when false. The do-while loop on the other hand first executes the set of arguments
and only then checks the condition. This means that the minimum number of times you can
execute a do-while loop is once. Let us now look at one example for each.
Forloop:
35
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
Whileloop:
Do while loop:
36
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
Ex-8 :- Study and practice on awk with relevant commands, syntax ,usage, application
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.
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
4. 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
➢ patternis a condition that specifies which lines of the input file should be processed.
➢ action is the set of commands to be executed on the lines that match the pattern.
➢ file is the name of the input file you want to process.
Example:
Consider the following text file as the input file for all cases below:
$cat > employee.txt
O/p:
ajay manager account 45000
sunil clerk account 25000
varun manager sales 50000
amit manager account 47000
tarun peon sales 15000
deepak clerk sales 23000
sunil peon sales 13000
satvik director purchase 80000
1. Default behavior of Awk: By default Awk prints every line of data from the specified
37
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
file.
$ awk '{print}' employee.txt
Output:
ajay manager account 45000
sunil clerk account 25000
varun manager sales 50000
amit manager account 47000
tarun peon sales 15000
deepak clerk sales 23000
sunil peon sales 13000
satvik director purchase 80000
In the above example, no pattern is given. So the actions are applicable to all the lines.
Action print without any argument prints the whole line by default, so it prints all the lines of
the file without failure.
Output:
ajay manager account 45000
varun manager sales 50000
amit manager account 47000
In the above example, the awk command prints all the line which matches with the
‘manager’.
3. Splitting a Line Into Fields : For each record i.e line, the awk command splits the record
delimited by whitespace character by default and stores it in the $n variables. If the line has 4
words, it will be stored in $1, $2, $3 and $4 respectively. Also, $0 represents the whole line.
$ awk '{print $1,$4}' employee.txt
Output:
ajay 45000
sunil 25000
varun 50000
amit 47000
tarun 15000
deepak 23000
sunil 13000
satvik 80000
In the above example, $1 and $4 represents Name and Salary fields respectively.
38
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
Ex 9 :- Study and practice on regular commands and the grep family with relevant
commands, syntax, usage, applications
Regular Expression provides an ability to match a “string of text” in a very flexible and
concise manner. A “string of text” can be further defined as a single character, word,
sentence or particular pattern of characters.
Like the shell’s wild–cards which match similar filenames with a single expression, grep
uses an expression of a different sort to match a group of similar patterns.
Examples :-
(c ) Use ^: The pattern following it must occur at the beginning of each line
$grep “^san” filename
Search lines beginning with san. It specifies the search pattern as
sanjeev ,sanjay, sanrit , sanchit , sandeep etc.
$ls –l |grep “^d”
Display list of directories only
$ls –l |grep “^-”
Display list of regular files only
(d) Use ^ with [ ]: The pattern must not contain any character in the set specified
$grep “New[^a-c]” filename
39
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
It specifies the pattern containing the word “New” followed by any character other than an
‘a’,’b’, or ‘c’
$grep “^[^a-z A-Z]” filename
Search lines beginning with an non-alphabetic character
(e) Use $: The pattern preceding it must occur at the end of each line
$ grep "vedik$" file.txt
40
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
Ex 10 :- Study and practice on compilation process of c program
The compilation is the process of converting the source code of the C language into machine
code. As C is a mid-level language, it needs a compiler to convert it into an executable code
so that the program can be run on our machine.
The C program goes through the following phases during compilation:
Compilation Process in C
How do we compile and run a C program?
We first need a compiler and a code editor to compile and run a C Program. The below
example is of an Ubuntu machine with GCC compiler.
1. Pre-processing
This is the first phase through which source code is passed. This phase includes:
➢ Removal of Comments
➢ Expansion of Macros
➢ Expansion of the included files.
➢ Conditional compilation
The preprocessed output is stored in the filename.I Let’s see what’s inside filename.i:
using $vi filename.i
In the above output, the source file is filled with lots and lots of info, but in the end, our code
is preserved.
➢ printf contains now a + b rather than add(a, b) that’s because macros have expanded.
➢ Comments are stripped off.
➢ #include<stdio.h> is missing instead we see lots of code. So header files have been
expanded and included in our source file.
➢ Conditional compilation provides a way of including or omitting selected lines of source
code depending on the values of literals specified by the DEFINE directive.
2. Compiling
The next step is to compile filename.i and produce an; intermediate compiled output
file filename.s. This file is in assembly-level instructions.
3. Assembling
42
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
In this phase the filename.s is taken as input and turned into filename.o by the assembler.
This file contains machine-level instructions. At this phase, only existing code is converted
into machine language, and the function calls like printf() are not resolved. Let’s view this
file using $vi filename.o
Binary Code
4. Linking
This is the final phase in which all the linking of function calls with their definitions is done.
Linker knows where all these functions are implemented. Linker does some extra work also,
it adds some extra code to our program which is required when the program starts and ends.
For example, there is a code that is required for setting up the environment like passing
command line arguments. This task can be easily verified by using $size
filename.o and $size filename. Through these commands, we know how the output file
increases from an object file to an executable file. This is because of the extra code that
Linker adds to our program.
43
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
Basic Viva Questions and Answers
1. What is Linux?
o Linux is an open-source, Unix-like operating system based on the Linux kernel,
developed by Linus Torvalds in 1991.
2. What is an operating system (OS)?
o An OS is system software that manages hardware and software resources and
provides services for computer programs.
3. What is the difference between Linux and Unix?
o Unix is a proprietary operating system developed in the 1970s, while Linux is
open-source and Unix-like, offering similar functionality but with free and
collaborative development.
4. What are the main components of the Linux operating system?
o The Kernel, System Libraries, and System Utilities.
5. What is the kernel in Linux?
o The kernel is the core part of Linux, responsible for managing hardware
resources and providing services to applications.
6. What is a shell in Linux?
o A shell is a command-line interface that allows users to interact with the
operating system by executing commands.
7. Explain the difference between kernel mode and user mode.
o Kernel mode has unrestricted access to system resources, while user mode is
restricted to prevent accidental system damage.
8. What does open-source mean?
o Open-source refers to software with publicly available source code, allowing
users to modify and distribute it freely.
9. What is multi-user capability in Linux?
o It means multiple users can access system resources simultaneously without
interfering with each other.
10.What is the difference between a process and a program?
o A program is a set of instructions, while a process is a running instance of a
program.
44
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
45
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
Experiment 2: VI Editor
46
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
47
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
Experiment 4: Filters
48
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
49
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
50
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
51
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
Experiment 8: AWK
1. What is AWK?
o A text processing tool.
2. How do you print every line using AWK?
o awk '{print}' file.txt
3. Explain $1 in AWK.
o Refers to the first field.
4. What does awk '/pattern/ {print}' do?
o Prints lines matching the pattern.
5. How do you print specific columns?
o awk '{print $1, $2}' file.txt
6. Explain the use of BEGIN.
o Executes actions before processing.
7. What is END in AWK?
o Executes actions after processing.
8. How do you calculate sums with AWK?
o awk '{sum+=$1} END {print sum}' file.txt
9. Explain FS in AWK.
o Sets the field separator.
10.What is NR in AWK?
o Current record number.
11.How do you format output in AWK?
o Use printf.
12.Explain pattern matching in AWK.
o Uses regular expressions.
13.How do you filter data with conditions?
o awk '$1 > 100 {print}' file.txt
14.What is OFS in AWK?
o Sets the output field separator.
15.How do you print line numbers?
o awk '{print NR, $0}' file.txt
52
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
53
R.BHANU SANKAR
Sanketika Vidya Parishad Engineering College
1. What is compilation?
o Converting source code to machine code.
2. Name the first phase of compilation.
o Preprocessing.
3. What command compiles C programs?
o gcc
4. Explain the -o option in gcc.
o Specifies output filename.
5. What is a.out?
o Default executable.
6. How do you link object files?
o gcc file1.o file2.o
7. What happens in the assembly phase?
o Converts to assembly code.
8. Explain the role of a linker.
o Resolves function calls.
9. What does gcc -Wall do?
o Enables all warnings.
10.How do you run an executable?
o ./filename
11.Explain the use of size command.
o Displays section sizes of a binary.
12.What is filename.i?
o Preprocessed output.
13.How do you generate an object file?
o gcc -c file.c
14.What is filename.s?
o Assembly code.
15.What does filename.o contain?
o Machine-level instructions.
54
R.BHANU SANKAR