0% found this document useful (0 votes)
15 views68 pages

LINUX LAB MANUEL-AUCE

Linux is an open-source operating system that shares similarities with Unix and consists of three main components: Kernel, System Library, and System Utility. It features portability, multi-user capabilities, and a hierarchical file system, and it is widely used across various devices, including servers and smartphones. The document also provides an extensive list of Linux commands categorized by their functions, such as file management, user management, and networking.

Uploaded by

pranee.eswar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views68 pages

LINUX LAB MANUEL-AUCE

Linux is an open-source operating system that shares similarities with Unix and consists of three main components: Kernel, System Library, and System Utility. It features portability, multi-user capabilities, and a hierarchical file system, and it is widely used across various devices, including servers and smartphones. The document also provides an extensive list of Linux commands categorized by their functions, such as file management, user management, and networking.

Uploaded by

pranee.eswar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

INTRODUCTION 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 17 September 1991 by Linus Torvalds.

Components of Linux System


Linux Operating System has primarily three components
 Kernel − Kernel is the core part of Linux. It is responsible for all major activities of this operating system. It
consists of various modules and it interacts directly with the underlying hardware. Kernel provides the required
abstraction to hide low level hardware details to system or application programs.
 System Library − System libraries are special functions or programs using which application programs or
system utilities accesses Kernel's features. These libraries implement most of the functionalities of the operating
system and do not requires kernel module's code access rights.
 System Utility − System Utility programs are responsible to do specialized, individual level tasks.
Kernel Mode vs User Mode
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.
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.
Basic Features
Following are some of the important features of the Linux Operating System.
 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 multiuser 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 the
same time.
 Hierarchical File System − Linux provides a standard file structure in which system files/ user files are
arranged.
 Shell − Linux provides a special interpreter program that can be used to execute commands of the operating
system. It can be used to do various types of operations, call application programs. etc.
 Security − Linux provides user security using authentication features like password protection/ controlled access
to specific files/ encryption of data.

Architecture
The following illustration shows the architecture of a Linux system −
The architecture of a Linux System consists of the following layers −

 Hardware layer − Hardware consists of all peripheral devices (RAM/ HDD/ CPU etc).
 Kernel − It is the core component of the Operating System, interacts directly with hardware, and provides low-
level services to upper-layer components.
 Shell − An interface to the kernel, hiding the complexity of the kernel's functions from users. The shell takes
commands from the user and executes the kernel's functions.
 Utilities − Utility programs that provide the user with most of the functionalities of operating systems.

Uses of Linux OS:

Several quantitative studies of open-source/free software concentrate on topics, such as reliability and market share,
with many studies examining Linux specifically. The Linux market is developing, and the Linux OS market size is
supposed to see a development of 19.2% by 2027, reaching 15.64 billion dollars, compared to 3.89 billion in 2019.
Proponents and analysts attribute the associative Linux success to its freedom, low cost, reliability, and security from
vendor lock-in.
UNIX VS LINUX:
Today Linux is in great demand. You can see the use of Linux everywhere. It's dominating our servers, desktop, and
smartphones and is even used in some electrical devices like refrigerators.
Some people think of Unix and Linux as synonyms, but that's not true. Many operating systems were developed to be
like Unix but none of them got the popularity of Linux. Linux is a clone of Unix. It has several features similar to Unix,
but still has some key differences. Before Linux and Windows, the computer world was dominated by Unix. Unix is a
copyrighted name and IBM AIX, HP-UX, and Sun Solaris are the only Unix operating systems that remained to date.
Linux Commands List with Examples
The Linux command is a utility of the Linux operating system. All basic and advanced tasks can be done by executing
commands. The commands are executed on the Linux terminal. The terminal is a command-line interface to interact
with the system, which is similar to the command prompt in the Windows OS. Commands in Linux are case-sensitive.
Linux terminal is a user-friendly terminal as it provides various support options. To open the Linux terminal, press
"CTRL + ALT + T" keys together, and execute a command by pressing the 'ENTER' key.
These commands are very useful for a beginner and professional both. We have divided these commands into following
sections so that you can easily identify their usage:
1. Linux Directory Commands
2. Linux File Commands
3. Linux File Content Commands
4. Linux User Commands
5. Linux Filter Commands
6. Linux Utility Commands
7. Linux Networking Command
1. Linux Directory Commands
1. pwd Command
The pwd command is used to display the location of the current working directory.
Syntax:
pwd
Output:

2. mkdir Command
The mkdir command is used to create a new directory under any directory.
Syntax:
mkdir <directory name>
Output:

3. rmdir Command
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. cd Command
The cd command is used to change the current directory.
Syntax:
cd <directory name>
Output:

2, Linux File commands


6. touch Command
The touch command is used to create empty files. We can create multiple empty files by executing it once.
Syntax:
touch <file name>
touch <file1> <file2> ....
Output:

7. cat Command
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 > <file name>
// Enter file content
Press "CTRL+ D" keys to save the file. To display the content of the file, execute it as follows:
cat <file name>
Output:

8. rm Command
The rm command is used to remove a file.
Syntax:
rm <file name>
Output:

9. cp Command
The cp command is used to copy a file or directory.
Syntax:
To copy in the same directory:
cp <existing file name> <new file name>
To copy in a different directory:
Output:

10. mv Command
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:

11. rename Command


The rename command is used to rename files. It is useful for renaming a large group of files.
Syntax:
rename 's/old-name/new-name/' files
For example, to convert all the text files into pdf files, execute the below command:
rename 's/\.txt$/\.pdf/' *.txt
Output:

3. Linux File Content Commands


12. head Command
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:
13. 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:
tail <file name>
Output:

14. tac Command


The tac command is the reverse of cat command, as its name specified. It displays the file content in reverse order (from
the last line).
Syntax:
tac <file name>
Output:

15. more command


The more command is quite similar to the cat command, as it is used to display the file content in the same way that the
cat command does. The only difference between both commands is that, in case of larger files, the more command
displays screenful output at a time.
In more command, the following keys are used to scroll the page:
ENTER key: To scroll down page by line.
Space bar: To move to the next page.
b key: To move to the previous page.
/ key: To search the string.
Syntax:
more <file name>
Output:
16. less Command
The less command is similar to the more command. It also includes some extra features such as 'adjustment in width
and height of the terminal.' Comparatively, the more command cuts the output in the width of the terminal.
Syntax:
less <file name>
Output:

4. Linux User Commands


17. su Command
The su command provides administrative access to another user. In other words, it allows access of the Linux shell to
another user.
Syntax:
su <user name>
Output:

18. id Command
The id command is used to display the user ID (UID) and group ID (GID).
Syntax:
id
Output:

19. useradd Command


The useradd command is used to add or remove a user on a Linux server.
Syntax:
useradd username
Output:

20. passwd Command


The passwd command is used to create and change the password for a user.
Syntax:
passwd <username>
Output:

21. groupadd Command


The groupadd command is used to create a user group.
Syntax:
groupadd <group name>
Output:

5. Linux Filter Commands


22. cat Command
The cat command is also used as a filter. To filter a file, it is used inside pipes.
Syntax:
cat <fileName> | cat or tac | cat or tac |. . .
Output:
23. cut Command
The cut command is used to select a specific column of a file. The '-d' option is used as a delimiter, and it can be a space
(' '), a slash (/), a hyphen (-), or anything else. And, the '-f' option is used to specify a column number.
Syntax:
cut -d(delimiter) -f(columnNumber) <fileName>
Output:

24. grep Command


The grep is the most powerful and used filter in a Linux system. The 'grep' stands for "global regular expression print."
It is useful for searching the content from a file. Generally, it is used with the pipe.
Syntax:
command | grep <searchWord>
Output:

25. comm Command


The 'comm' command is used to compare two files or streams. By default, it displays three columns, first displays non-
matching items of the first file, second indicates the non-matching item of the second file, and the third column displays
the matching items of both files.
Syntax:
comm <file1> <file2>
Output:

26. sed command


The sed command is also known as stream editor. 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:

27. tee command


The tee command is quite similar to the cat command. The only difference between both filters is that it puts standard
input on standard output and also write them into a file.
Syntax:
cat <fileName> | tee <newFile> | cat or tac |.....
Output:

28. tr Command
The tr command is used to translate the file content like from lower case to upper case.
Syntax:
command | tr <'old'> <'new'>
Output:

29. uniq Command


The uniq command is used to form a sorted list in which every word will occur only once.
Syntax:
command <fileName> | uniq
Output:

30. wc Command
The wc command is used to count the lines, words, and characters in a file.
Syntax:
wc <file name>
Output:

31. od Command
The od command is used to display the content of a file in different s, such as hexadecimal, octal, and ASCII characters.
Syntax:
od -b <fileName> // Octal format
od -t x1 <fileName> // Hexa decimal format
od -c <fileName> // ASCII character format
Output:

32. sort Command


The sort command is used to sort files in alphabetical order.
Syntax:
sort <file name>
Output:
33. gzip Command
The gzip command is used to truncate the file size. It is a compressing tool. It replaces the original file by the compressed
file having '.gz' extension.
Syntax:
gzip <file1> <file2> <file3>...
Output:

34. gunzip Command


The gunzip command is used to decompress a file. It is a reverse operation of gzip command.
Syntax:
gunzip <file1> <file2> <file3>. .
Output:

6. Linux Utility Commands


35. find Command
The find command is used to find a particular file within a directory. It also supports various options to find a file such
as byname, by type, by date, and more.
The following symbols are used after the find command:
(.) : For current directory name
(/) : For root
Syntax:
find . -name "*.pdf"
Output:
36. locate Command
The locate command is used to search a file by file name. It is quite similar to find command; the difference is that it is
a background process. It searches the file in the database, whereas the find command searches in the file system. It is
faster than the find command. To find the file with the locates command, keep your database updated.
Syntax:
locate <file name>
Output:

37. date Command


The date command is used to display date, time, time zone, and more.
Syntax:
date
Output:

38. cal Command


The cal command is used to display the current month's calendar with the current date highlighted.
Syntax:
cal<
Output:

39. sleep Command


The sleep command is used to hold the terminal by the specified amount of time. By default, it takes time in seconds.
Syntax:
sleep <time>
Output:

40. time Command


The time command is used to display the time to execute a command.
Syntax:
time
Output:

41. zcat Command


The zcat command is used to display the compressed files.
Syntax:
zcat <file name>
Output:

42. df Command
The df command is used to display the disk space used in the file system. It displays the output as in the number of used
blocks, available blocks, and the mounted directory.
Syntax:
df
Output:

43. mount Command


The mount command is used to connect an external device file system to the system's file system.
Syntax:
mount -t type <device> <directory>
Output:

44. exit Command


Linux exit command is used to exit from the current shell. It takes a parameter as a number and exits the shell with a
return of status number.
Syntax:
exit
Output:

After pressing the ENTER key, it will exit the terminal.


45. clear Command
Linux clear command is used to clear the terminal screen.
Syntax:
clear
Output:

After pressing the ENTER key, it will clear the terminal screen.
7. Linux Networking Commands
46. ip Command
Linux ip command is an updated version of the ipconfig command. It is used to assign an IP address, initialize an
interface, disable an interface.
Syntax:
ip a or ip addr
Output:

47. ssh Command


Linux ssh command is used to create a remote connection through the ssh protocol.
Syntax:
ssh user_name@host(IP/Domain_name)</p>
48. mail Command
The mail command is used to send emails from the command line.
Syntax:
mail -s "Subject" <recipient address>
Output:

49. ping Command


The ping command is used to check the connectivity between two nodes, that is whether the server is connected. It is a
short form of "Packet Internet Groper."
Syntax:
ping <destination>
Output:

50. host Command


The host command is used to display the IP address for a given domain name and vice versa. It performs the DNS
lookups for the DNS Query.
Syntax:
host <domain name> or <ip address>
Output:
Ex-1: Study and practice file system / handling files with commands, syntax, usage, and application.
Linux File System:
A Linux file system is a structured collection of files on a disk drive or a partition. A partition is a segment of memory
that contains some specific data. In our machine, there can be various partitions of the memory. Generally, every
partition contains a file system.
Linux file system is generally a built-in layer of a Linux operating system used to handle the data management of the
storage. It helps to arrange the file on the disk storage. It manages the file name, file size, creation date, and much more
information about a file.

There may be below reasons for maintaining the file system:

o Primarily the computer saves data to the RAM storage; it may lose the data if it gets turned off. However, there
is non-volatile RAM (Flash RAM and SSD) that is available to maintain the data after the power interruption.
o Data storage is preferred on hard drives as compared to standard RAM as RAM costs more than disk space. The
hard disks costs are dropping gradually comparatively the RAM.

The Linux file system contains the following sections:

o e root directory (/)


o A specific data storage format (EXT3, EXT4, BTRFS, XFS and so on)
o A partition or logical volume having a particular file system.
Linux File System Structure:
Linux file system has a hierarchal file structure as it contains a root directory and its subdirectories. All other directories
can be accessed from the root directory. A partition usually has only one file system, but it may have more than one file
system.

Types of Linux File System:


When we install the Linux operating system, Linux offers many file systems such as Ext, Ext2, Ext3, Ext4, JFS,
ReiserFS, XFS, btrFs, and swap.
Linux mount
The mount command attaches the filesystem of an external device to the filesystem of a system.
It instructs the operating system that filesystem is ready to use and associate it with a particular point in the system's
hierarchy. Mounting will make files, directories and devices available to the users.
It mounts the external storage devices like hard disks, pen drives, USBs etc.
Conversely, umount command unmount the mount point and detach the device from the system.
To mount a device generally, following syntax is used
Syntax:

mount -t type <device> <directory>


List currently mounted file systems
This command display all currently mounted file system on a system.
Syntax:
mount

Linux Create File:


Linux file system considers everything as a file in Linux; whether it is text file images, partitions, compiled programs,
directories, or hardware devices. If it is not a file, then it must be a process. To manage the data, it forms a tree structure.
Linux files are case sensitive, so test.txt and Test.txt will be considered as two different files. There are multiple ways
to create a file in Linux. Some conventional methods are as follows:
o using cat command
o using touch command
o using redirect '>' symbol
o using echo command
o using printf command
Apart from all of the above methods, we can also create a file from the desktop file manager. Let's understand the above
methods in detail:
1. Using cat command
The cat command is one of the most used commands in Linux. It is used to create a file, display the content of the
file, concatenate the contents of multiple files, display the line numbers, and more.
Here, we will see how to create files and add content to them using cat command.
First of all, create a directory and named it as New_directory, execute the mkdir command as follows:

mkdir New_directory
Change directory to it:

cd New_directory
Output:

Now execute the cat command to create a file:

cat > test.txt


The above command will create a text file and will enter in the editor mode. Now, enter the desired text and press CTRL
+ D key to save and exit the file and it will return to the command line.
To display the content of the file, execute the cat command as follows:

cat test.txt
Consider the below output:

2. Using the touch command


The touch command is also one of the popular commands in Linux. It is used to create a new file, update the time
stamp on existing files and directories. It can also create empty files in Linux.
The touch command is the simplest way to create a new file from the command line. We can create multiple files by
executing this command at once.
To create a file, execute the touch command followed by the file name as given below:

touch test1.txt
To list the information of the created file, execute the below command:

ls - l test1.txt
Consider the below output:
To create multiple files at once, specify files and their extensions after the touch command along with single space.
Execute the below command to create three files at once:

touch test1.txt test2.txt test3.txt


To create two different types of file, execute the command as follows:

touch test4.txt test.odt


The above command will create two different files named as test4.txt and test.odt.
To display the file and its timestamp, execute the ls command as follows:

ls -l
Consider the below output:

If we pass the name of an existing file, it will change the timestamp of that file.
Note: The significant difference between touch and cat command is that using cat command, we can specify the
content of the file from the command prompt comparatively the touch command creates a blank file.
3. Using the redirect (>) symbol
We can also create a file using the redirect symbol (>) on the command line. To create a file, we just have to type a
redirect symbol (>) followed by the file name. This symbol is mostly used to redirect the output. There are two ways to
redirect the output. If we use > operator, it will overwrite the existing file, and >> operator will append the output.
To create a file with redirect (>) operator, execute the command as follows:

> test5.txt
The above command will create a file, to display the existence of the created file, execute the below command:

ls -l test5.txt
Consider the below output:

4. Using echo command


The echo command is used to create a file, but we should specify the file content on the command line.
To create the file with the echo command, execute the command as follows:

echo " File content" > test6.txt


The above command will create the test6 file. To display the existence of the file, execute the below command:

ls -l test6.txt
consider the below output:

5. Using printf command


We can also create a file using printf command. For this we need to specify the file content on the command line.
To create a file with the printf command, execute the command as follows:

printf " File content" > test7.txt


To display the file details, execute the ls command as follows:

ls -l test7.txt
To display the file content, execute the cat command as follows:

cat test7.txt
Consider the below output:

6. Using Text Editor


We can also create a file using the different text editors like vim, nano, vi, and more.

o Using Vim text editor


We can create a file using the Vim text editor. If you do not have the vim editor installed on your machine, execute the
below command:

sudo apt install vim


Output:
[sudo] password for javatpoint:
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
vim-runtime
Suggested packages:
ctags vim-doc vim-scripts
The following NEW packages will be installed:
vim vim-runtime
0 upgraded, 2 newly installed, 0 to remove and 64 not upgraded.
Need to get 6,878 kB of archives.
After this operation, 33.4 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://in.archive.ubuntu.com/ubuntu eoan/main amd64 vim-runtime all 2:8.1.0875-5ubuntu2 [5,669 kB]
Get:2 http://in.archive.ubuntu.com/ubuntu eoan/main amd64 vim amd64 2:8.1.0875-5ubuntu2 [1,209 kB]
Fetched 6,878 kB in 3s (2,256 kB/s)
Selecting previously unselected package vim-runtime.
(Reading database ... 216385 files and directories currently installed.)
Preparing to unpack .../vim-runtime_2%3a8.1.0875-5ubuntu2_all.deb ...
Adding 'diversion of /usr/share/vim/vim81/doc/help.txt to /usr/share/vim/vim81/doc/
help.txt.vim-tiny by vim-runtime'
Adding 'diversion of /usr/share/vim/vim81/doc/tags to /usr/share/vim/vim81/doc/tags
.vim-tiny by vim-runtime'
Unpacking vim-runtime (2:8.1.0875-5ubuntu2) ...
Selecting previously unselected package vim.
Preparing to unpack .../vim_2%3a8.1.0875-5ubuntu2_amd64.deb ...
Unpacking vim (2:8.1.0875-5ubuntu2) ...
Setting up vim-runtime (2:8.1.0875-5ubuntu2) ...
Setting up vim (2:8.1.0875-5ubuntu2) ...
update-alternatives: using /usr/bin/vim.basic to provide /usr/bin/vim (vim) in auto
mode
update-alternatives: using /usr/bin/vim.basic to provide /usr/bin/vimdiff (vimdiff)
in auto mode
update-alternatives: using /usr/bin/vim.basic to provide /usr/bin/rvim (rvim) in au
to mode
update-alternatives: using /usr/bin/vim.basic to provide /usr/bin/rview (rview) in
auto mode
update-alternatives: using /usr/bin/vim.basic to provide /usr/bin/vi (vi) in auto m
ode
update-alternatives: using /usr/bin/vim.basic to provide /usr/bin/view (view) in au
to mode
update-alternatives: using /usr/bin/vim.basic to provide /usr/bin/ex (ex) in auto m
ode
Processing triggers for man-db (2.8.7-3) ...
The Vim text editor is successfully installed.
To create a file using the vim text editor, execute the below command:

vim test8.txt
The above command will open the text editor, press i key to go to the insert mode of the editor.
Enter the file content, press Esc key preceded by :wq to save and exit the file. The text editor looks like as follows:

To display the file information, execute the ls command as follows:


ls -l test8.txt
To view the file content, run the cat command as follows:

cat test8.txt
Consider the below output:

7. Using Nano editor


We can create a file using the nano text editor. To create a file, execute the below command:

nano test9.txt
The above command will open the nano text editor. Enter the desired text and press CTRL + X then type y for
confirmation of the file changes. Press Enter key to exit from the editor.
The nano text editor looks like the below image:

To display the file information, execute the below command:

ls -l test9.txt
To view the file content, execute the below command:

cat test9.txt
Consider the below output:

Linux file command

file command is used to determine the file type. It does not care about the extension used for file. It simply uses file
command and tell us the file type. It has several options.

Syntax:

file <filename>
Example:

file 1.png
Linux File Command Options

Option Function

file -s Used for special files.

file * Used to list types of all the files.

file /directory name/* Used to list types of all the files from mentioned directory.

file [range]* It will list out all the files starting from the alphabet present within the given range.
Ex-2: Practice on vi editor.
What is the VI editor?
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 endless 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
 Commands are case sensitive. You should use the right letter case.
vi Editor Insert mode:
 This mode is for inserting text in the file.
 You can switch to the Insert mode from the command mode by pressing ‘i’ on the keyboard
 Once you are in Insert mode, any key would be taken as an input for the file on which you are currently working.
 To return to the command mode and save the changes you have made you need to press the Esc key
How to use vi editor
To launch the VI Editor -Open the Terminal (CLI) and type
vi <filename_NEW> or <filename_EXISTING>
And if you specify an existing file, then the editor would open it for you to edit. Else, you can create a new file.
VI Editing commands
 i – Insert at cursor (goes into insert mode)
 a – Write after cursor (goes into insert mode)
 A – Write at the end of line (goes into insert mode)
 ESC – Terminate insert mode
 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 3 lines.
 D – Delete contents of line after the cursor
 C – Delete contents of a line after the cursor and insert new text. Press ESC key to end insertion.
 dw – Delete word
 4dw – Delete 4 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 these 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 insert mode by pressing a, A, o, as required.
Moving within a file
 k – Move cursor up
 j – Move cursor down
 h – Move cursor left
 l – Move cursor right
You need to be in the command mode to move within a file. The default keys for navigation are mentioned below else;
You can also use the arrow keys on the keyboard.
Saving and Closing the file
 Shift+zz – Save the file and quit
 :w – Save the file but keep it open
 :q! – Quit vi and do not save changes
 :wq – Save the file and quit
You should be in the command mode to exit the editor and save changes to the file.
To create a file with Vi editor, execute the below command:
vi test10.txt
The above command will open the Vi editor. Press i key for the insert mode and enter the file content. Press Esc key
and :wq to save and exit the file from the editor.
To display the file information, execute the below command:
ls -l test10.txt
To display the file content, execute the below command:
cat test10.txt
Consider the below output:
Ex-3: Study and practice on redirection operators with relevant commands, syntax, usage and
application.
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 a command.
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 pipesymbol '|').
Standard Streams In I/O Redirection
The bash shell has three standard streams in I/O redirection:
o standard input (stdin) : The stdin stream is numbered as stdin (0). The bash shell takes input from stdin. By
default, keyboard is used as input.
o standard output (stdout) : The stdout stream is numbered as stdout (1). The bash shell sends output to stdout.
Output goes to display.
o standard error (stderr) : The stderr stream is numbered as stderr (2). The bash shell sends error message to
stderr. Error message goes to display.

1. Linux Input Redirection


< stdin
The bash shell uses stdin to take input. In input redirection, a file is made input to the command and this redirection is
done with the help of '<' sign.
Syntax:
cat < <fileName>
Example:
cat < file.txt

Look at the above snapshot, command "cat < file.txt" has taken 'file.txt' as input and displayed its content.
2. Linux Output Redirection
Output redirection is used to put output of one command into a file or into another command.
> stdout
The stdout is redirected with a '>' greater than 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'.
Output File Is Erased
In output redirection, during scanning of a command line, shell will encounter through '>' sign and will clear the file.
Example:
zcho Welcome > afile.txt

Look at the above snapshot, command "zcho Welcome > afile.txt" is wrong but still file 'afile.txt' is cleared.
3. Linux Error Redirection
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:
zcho hyii 2> /dev/null

Look at the above snapshot, by using command "zcho hyii 2> /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.

2>&1
This command helps in redirecting the stdout and stderr in the same file.
Example:
newfile.txt > abc.txt and error.txt 2>&1
Look at the above snapshot, 'abc.txt and error.txt' is directing to the same file 'newfile.txt'.
Note: Order of redirections is really important.
If you'll write:
ls > dirlist 2>&1
then, stdout and stderr both will be directed to the file dirlist.
But if you'll write:
ls 2>&1 > dirlist
then, only stdout will be redirected to dirlist. This is because, before the stdout is redirected to dirlist, stderr has made a
copy of stdout.
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. cut
3. grep
4. comm
5. sed
6. tee
7. tr
8. uniq
9. wc
10. od
11. sort
12. gzip

1. Linux Cat Filters


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:
cat weeks.txt | tac | cat | cat | tac

Look at the above snapshot, output of one 'cat' or 'tac' command is passing onto another as input.
2. Linux cut Command
Linux cut command is useful for selecting a specific column of a file. It is used to cut a specific sections by byte position,
character, and field and writes them to standard output. It cuts a line and extracts the text data. It is necessary to pass an
argument with it; otherwise, it will throw an error message.
To cut a specific section, it is necessary to specify the delimiter. A delimiter will decide how the sections are separated
in a text file. Delimiters can be a space (' '), a hyphen (-), a slash (/), or anything else. After '-f' option, the column number
is mentioned.
Syntax:
cut OPTION... [FILE]...
Options:
The following command line options are used by the cut command to make it more specific:
-b, --bytes=LIST: It is used to cut a specific section by bytes.
-c, --characters=LIST: It is used to select the specified characters.
-d, --delimiter=DELIM: It is used to cut a specific section by a delimiter.
-f, --fields=LIST: It is used to select the specific fields. It also prints any line that does not contain any delimiter
character, unless the -s option is specified.
-n: It is used to ignore any option.
--complement: It is used to complement the set of selected bytes, characters or fields
Cut by Character
The '-c' option is used to cut a specific section by character. However, these character arguments can be a number or a
range of numbers, a list of comma-separated numbers, or any other character.
To cut by specified character, execute the command as follows:
cut -c < characters> <file name>
Consider the below commands:
cut -c 1,6 exm.txt
cut -c 1-3 exm.txt
The above commands will cut the line by the specified characters. Consider the below output:

From the above output, we can see the first command is cutting the first and sixth character from each line, and the
second command is cutting the first to the third character from each line.

3. Grep Command in Linux/Unix


The 'grep' command stands for "global regular expression print". grep command filters the content of a file which
makes our search easy.
How to install grep in Linux?
Grep comes pre-installed in almost every distribution of Linux. However, in case, we can install it with the below
command in the terminal window if it is missing from our system:
$ sudo apt-get install grep
grep with pipe
The 'grep' command is generally used with pipe (|).
Syntax:
command | grep <searchWord>
Example:
cat marks.txt | grep 9

Look at the above snapshot, grep command filters all the data containing '9'.
grep without pipe
It can be used without pipe also.
Syntax:
grep <searchWord> <file name>
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 -vM: 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 -v 9 marks.txt" displays lines hwich don't contain our search
word '9'.
o grep -i: The 'grep -i' command filters output in a case-insensitive way.
Syntax:
grep -i <searchWord> <fileName>
Example:
grep -i red exm.txt

Look at the above snapshot, command "grep -i red exm.txt" displays all lines containing 'red' whether in upper
case or lower case.
o grep -A/ grep -B/ grep -C
grep -A command is used to display the line after the result.
grep -B command is used to display the line before the result.
grep -C command is used to display the line after and line before the result.
You can use (A1, A2, A3.....)(B1, B2, B3....)(C1, C2, C3....) to display any number of lines.
Syntax:
grep -A<lineNumber> <searchWord> <fileName>
grep -B<lineNumber> <searchWord> <fileName>
grep -C<lineNumber> <searchWord> <fileName>
Example:
grep -A1 yellow exm.txt
grep -B1 yellow exm.txt
grep -C1 yellow exm.txt

Look at the above snapshot, command "grep -A1 yellow exm.txt" displays searched line with next succeeding line,
command "grep -B1 yellow exm.txt" displays searched line with one preceding line and command "grep -C1 yellow
exm.txt" displays searched line with one preceding and succeeding line.
4. Linux 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 non-matching 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 <file1> <file2>
Example:
comm file1.txt file2.txt

Look at the above snapshot,


First column displays non-matching items of first file 'file1.txt' (Sehwag, Yuvi)
Second column displays non-matching items of second file 'file2.txt' (Zadeja)
Third column indicates matching items of both the files (Dhoni, Dravid, Sachin)
To Display Single Column
If you want to output a single column, you have to specify number of the columns which are not to be displayed.
Syntax:
comm -23 (To display first column)
comm -13 (To display second column)
comm -12 (To display third column)
Example:
comm -23 file1.txt file2.txt
comm -13 file1.txt file2.txt
comm -12 file1.txt file2.txt

Look at the above snapshot, column number which needs to be displayed are not mentioned in the 'comm' command.
5. Linux sort
The 'sort' command sorts the file content in an alphabetical order.
Syntax:

sort <fileName>
Example:

sort weeks.txt

Look at the above snapshot, the 'sort' command has sorted the file 'weeks.txt' in alphabetical order.
To Sort A Column
If a file has more than one column, column number is used to sort a specific column.
Syntax:

sort -k<columnNumber> <fileName>


Example:

sort -k1 states.txt

ort -k2 states.txt

Look at the above snapshot, we have sorted column 1 and 2.


Numeric Sorting
Numeric sorting is different from alphabetical sorting. For numeric sorting option 'n' is used along with the column
number if required.
Syntax:

sort -n -k<columnNumber> <fileName>


Example:

sort -n -k2 marks.txt

6. Linux od
The 'od' term stands for octal dump. It displays content of a file in different human-readable formats like hexadecimal,
octal and ASCII characters.
Syntax:

od -b <fileName> (display files in octal format)

od -t x1 <fileName> (display files in hexadecimal bytes format)

od -c <fileName> (display files in ASCII (backslashed) character format)

Example:

od -b format.txt

od -t x1 format.txt

od -c format.txt
Look at the above snapshot, command "od -b format.txt" displays in octal format, command "od -t x1
format.txt" displays in hexadecimal format, command "od -c format.txt" displays in ASCII character where
a new line will be marked with '\n'
Ex-5: Study and practice on Backup with relevant commands, syntax, usage and applications.

Back-up Command in Linux/Unix:

cp Command : The cp command is used to copy directories and files.


Options of cp Command

Option Description

--attributes-only It doesn't copy the data of the file, only the attributes.

-b It is like backup but doesn't accept any argument.

--backup[=CONTROL] It makes a backup of all existing destination files.

--copy-contents When recursive, it copies special file contents.

--parents Under the directory, it uses the full source file name.

--recursive, -r, -R It recursively copies directories.

--reflink[=WHEN] It controls CoW/clone copies.

--remove-destination It removes all existing destination files before trying to open them
(opposed to --force).

--target-directory=DIRECTORY, It copies every SOURCE argument to DIRECTORY.


-t

--one-file-system, -x It stays on the file system.

--help It shows the help menu and exits.

--version It provides version details and exits.

To copy a file into the same directory syntax will be,

cp <existing file name> <new file name>


In above snapshot, we have created a copy of 'docu' and named it as 'newdocu'. If in case, <new file name> (in our
case it is 'newdocu') alreade exists, then it will simply over write the earlier file.

To copy a file in a different directory

We have to mention the path of the destination directory.

In the snapshot below, earlier there is no 'text' file. After giving the command, 'text' file has been copied to the
destination directory that is 'Desktop'.

Linux cp --backup
If the file you want to copy already exists in the destination directory, you can back-up your existing file with the use
of this command.
Syntax:

cp --backup <filename> <destinationDirectory>


Example:

cp --backup file2.txt /home/sssit/Downloads

As you can see above, 'file2.txt' already exists in the destination directory. Hence, we have created a backup of this file
and copied it in the same directory (having same name).
Ex-6: Study and practice on internet related commands, syntax, usage and applications.

Linux Networking Commands


Every computer is connected to some other computer through a network whether internally or externally to exchange
some information. This network can be small as some computers connected in your home or office, or can be large or
complicated as in large University or the entire Internet.
Maintaining a system's network is a task of System/Network administrator. Their task includes network configuration
and troubleshooting.
Here is a list of Networking and Troubleshooting commands:

ifconfig Display and manipulate route and network interfaces.

ip It is a replacement of ifconfig command.

traceroute Network troubleshooting utility.

tracepath Similar to traceroute but doesn't require root privileges.

ping To check connectivity between two nodes.

netstat Display connection information.

ss It is a replacement of netstat.

dig Query DNS related information.

nslookup Find DNS related query.

route Shows and manipulate IP routing table.

host Performs DNS lookups.

arp View or add contents of the kernel's ARP table.

iwconfig Used to configure wireless network interface.

hostname To identify a network name.

curl or wget To download a file from internet.

mtr Combines ping and tracepath into a single command.


whois Will tell you about the website's who is.

ifplugstatus Tells whether a cable is plugged in or not.

Explanation of the above commands:


ifconfig: ifconfig is short for interface configurator. This command is utilized in network inspection, initializing the
interface, enabling or disabling an IP address, and configuring an interface with an IP address. Also, it is used to show
the network and route interface.
The basic details shown with ifconfig are:

o MTU

o MAC address

o IP address
Syntax:

Ifconfig
ip: It is the updated and latest edition of ifconfig command. The command provides the information of every network,
such as ifconfig. Also, it can be used to get information about a particular interface.
Syntax:

ip a

ip addr
traceroute: The traceroute command is one of the most helpful commands in the networking field. It's used to balance
the network. It identifies the delay and decides the pathway to our target. Basically, it aids in the below ways:

o It determines the location of the network latency and informs it.

o It follows the path to the destination.

o It gives the names and recognizes all devices on the path.


Syntax:

traceroute <destination>
tracepath: The tracepath command is the same as the traceroute command, and it is used to find network delays.
Besides, it does not need root privileges. By default, it comes pre-installed in Ubuntu. It traces the path to the destination
and recognizes all hops in it. It identifies the point at which the network is weak if our network is not strong enough.
Syntax:

tracepath <destination>
ping: It is short for Packet Internet Groper. The ping command is one of the widely used commands for network
troubleshooting. Basically, it inspects the network connectivity between two different nodes.
Syntax:

ping <destination>
netstat: It is short for network statistics. It gives statistical figures of many interfaces, which contain open sockets,
connection information, and routing tables.
Syntax:

Netstat
ss: This command is the substitution for the netstat command. The ss command is more informative and much faster
than netstat. The ss command's faster response is possible because it fetches every information from inside the kernel
userspace.
Syntax:

Ss
nsloopup: The nslookup command is an older edition of the dig command. Also, it is utilized for DNS related problems.
Syntax:

nslookup <domainname>
dig: dig is short for Domain Information Groper. The dig command is an improvised edition of the nslookup command.
It is utilized in DNS lookup to reserve the DNS name server. Also, it is used to balance DNS related problems. Mainly,
it is used to authorize DNS mappings, host addresses, MX records, and every other DNS record for the best DNS
topography understanding.
Syntax:

dig <domainname>
route: The route command shows and employs the routing table available for our system. Basically, a router is used to
detect a better way to transfer the packets around a destination.
Syntax:

Route
host: The host command shows the IP address for a hostname and the domain name for an IP address. Also, it is used
to get DNS lookup for DNS related issues.
Syntax:

host -t <resourceName>
arp: The arp command is short for Address Resolution Protocol. This command is used to see and include content in
the ARP table of the kernel.
Syntax:

Arp
iwconfig: It is a simple command which is used to see and set the system's hostname.
Syntax:

Hostname
curl and wget: These commands are used to download files from CLI from the internet. curl must be specified with the
"O" option to get the file, while wget is directly used.
curl Syntax:

curl -O <fileLink>
wget Syntax:

wget <fileLink>
mtr: The mtr command is a mix of the traceroute and ping commands. It regularly shows information related to the
packets transferred using the ping time of all hops. Also, it is used to see network problems.
Syntax:

mtr <path>
whois: The whois command fetches every website related information. We can get every information of a website, such
as an owner and the registration information.
Syntax:

mtr <websiteName>
ifplugstatus: The ifplugstatus command checks whether a cable is currently plugged into a network interface. It is not
available in Ubuntu directly. We can install it with the help of the below command:

sudo apt-get install ifplugd


Syntax:

Ifplugstatus
iftop: The iftop command is utilized in traffic monitoring.
tcpdump: The tcpdump command is widely used in network analysis with other commands of the Linux network. It
analyses the traffic passing from the network interface and shows it. When balancing the network, this type of packet
access will be crucial.
Syntax:

$ tcpdump -i <network_device>
Ex-7: Study and practice on shells/shell programming with relevant programming constructs, syntax,
usage and applications.
Shell Programming in Linux
What is a shell?
Technically speaking in UNIX language, it is an interface between the user and operating system service. A
shell provides users with an interface that not only accepts human-readable commands but also executes
them.
An operating system consists of many parts, but the 2 core parts are the kernel and shell, we know that the
kernel is like the atom of the operating system, the sole heart of the operating system. The kernel works a
mediator between the software and hardware.
The shell on the other hand is more like the right hand of the kernel, it takes input from you in the form of
commands, processes it, and then gives an output. The shell is retrieved via the terminal that runs it. Shell
also provides an interface through which a user works on programs and scripts.
Types of shell
Shell is broadly classified into 2 categories:
1. Command line shell
The shell can be accessed by using a command-line interface, and we all know what a command line is. It is
nothing but the terminal in Linux – the lean, mean coding machine. The terminal is a special program to
type in the human-readable commands such as “cat”, “ls”, “cd”, “pwd”, “mkdir”, and a thousand more!
When you execute the commands, the result is then displayed on the terminal to the user. The terminal is
powerful and allows users to store commands in a file and execute them together. Linux is not the only
operating system with a command line, even windows had the command prompt and so doe mac OS
The command line is a boon for developers and administrators, but it may not be everyone’s cup of coffee as
memorizing so many command sand and an even longer list of options is not an easy task. That is why there
are 2 options for the shell so that users can use what they prefer most.
2. Graphical shell
The graphical shell is nothing but the GUI – Graphical interface design. The graphical shell provides an
interface for manipulating programs based on the graphical user interface. The GUI allows users to do bath
tasks that the terminal can and can not do.
For example, you can do tasks like allowing for operations such as opening, closing, moving, and resizing
windows, as well as switching focus between windows and more which the terminal can’t. The main
advantage of the GUI is that users need not type commands for every small task.
There are various shells that are available for Linux based operating systems, let us look at some of them:
1. BASH (Bourne Again SHell)
The bash shell is the most loved and commonly used shell in Linux-based operating systems. It is a default
login shell in Linux systems and in macOS, however, it can also be installed on Mi9crosoft Windows.
The prompt for the bash shell is a dollar sign ($). The bash shell is a derivative of the Bourne shell, other
derivatives of the Bourne shell include POSIX and Korn.
2. KSH (Korn SHell)
The Korn shell is also derived from the Bourne shell but is the base for POSIX. It was written, designed, and
developed by David Korn in the early 1980s Some features of KSH are:
a. It provides object-oriented programing since ksh93t.
b. It has many mathematical and dynamic search functions.
c. it is very similar to C language and even has C-language-like expressions
d. You get a choice of 3 command line editing styes: vi, Emacs, and Gosling.
e. KSH includes reference variables and hierarchically nested variables.
f. It has associative arrays and built-in floating-point arithmetic operators
g. the Korn shell provides process substitution and process redirection.
3. CSH (C shell)
The C shell was written, designed, and developed at the University of California by Bill Joy. J8ust like bash
has the prompt “$”, chs has the prompt “%”. The C shell was developed to be very similar to the C
programming language, it also includes useful programming features like in-built support for arithmetic
operations
The C shell feature ‘aliases’ and command history which was missing in different types of shells in Linux
like the Bourne shell. The complete pathname for the C shell is /bin/sch.
There are many other shells available like:
 ZSH (Z shell)
 Fish Shell
 POSIX
 TENEX
What is shell scripting?
We saw that shells are interactive, they accept commands as input from users and execute them. But if we
want to execute a bunch of commands again and again (like a loop), we have to type in all commands each
time in the terminal.
To avoid this, the shell can also take in the commands as the input from a file, where we can compile all of
these commands and execute them. These files are called Shell programs or shell scripts and have the
extension of “.sh”.
Shell programs, just like any other programming language in the world, have a specific syntax and a set of
rules. A shell script contains the following elements:
 Keywords: if, else, break continue, etc.
 Commands: cd, ls, echo, touch, cat, pwd, mkdir, etc.
 Loops: if…then…else, while…do, do…while, case, etc.
 Functions
We will look at each of the above-mentioned and more in detail in the practical part.
Why use shell programming?
There are a gazillion reasons why you should use shell programming, here are a few:
1. Avoids repetitive work and automation
2. Helps in system monitoring
3. Used for routine backups
4. Adding new functionality to shell
5. Creating custom filters
7. Helps in automating various tasks
8. Changing time and date
9. Printing current working directory
10. Scheduling jobs
Advantages of shell programming
Again, if we start writing the advantages of the list advantages of shell programming, it may never end,
nonetheless here are 8 advantages of it:
 Easy to use
 Portable
 Qiuck start
 Interactive debugging
 Same syntax as that of command line
 Avoids repetitive work and automation
 Shell scripting is much quicker than writing commands in the terminal
 Simple up learn
Disadvantages of shell programming
They say that every good thing has its negatives, which also hold true for shell programming, here are some
of its disadvantages:
 Slow execution speed
 Not suited for large and complex tasks
 Design flaws within the language syntax
 Provides minimal data structure, unlike other scripting languages
 Prone to costly errors
Creating a shell program
We saw that to write a shell program we need to write it in a “.sh” file, meaning that a regular “.txt” or
“.odt” or “.doc” will not suffice. Now there are a hundred ways to create a “.sh” file, let us look at some
alternatives:
1. Using ‘gedit’
One method of creating a “.sh” file is by using the edit command. You can directly create and open a “.sh”
file by specifying the name of the file as shown below, or you can simply use the edit command and save the
file and name it later.

You must be careful while naming your file because if you write the name of an already existing file with
the command, it will open the existing file instead of creating one.
2. Using nano editor
Another method to create a “.sh” file is by using the nano editor in Linux-based operating systems. It works
similar 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 new
one if you enter the name of an already existing file.
3. Using Vi editor
We all know that the Vi editor is a really powerful editor for text manipulation, but not that easy for text
creation, meaning it will be even harder to write shell programs in it. Nonetheless, 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.
4. Using the GUI
We know that all the distributions of Linux come with LibreOffice preinstalled, you can simply open a new
file, write your program, and while saving your file, simply add the extension “.sh” to your filename as
shown:

These are just some of the ways you can use to create a “.sh” file to write your shell program in. Now that
we have laid down the fundamentals, let us jump into the theoretical part as we look at things like variables,
expression loops, and more.
Printing “Hello world”
Let us kick start our shell programming journey by starting with the cliched “Hello world” program. Our
objective is very simple and straightforward, and all we need to do is print the text “Hello world”
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 bash shell.
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:
sh <filename>.sh

And voila! We just printed “Hello ”


Writing comments in the shell programs
We all know that writing comments is one of the most important habits while writing a code, we write it in
order to understand what is actually happening. In shell programming, we write comments starting with a
hash “#”, this makes these lines nonexecutable.
Printing using the echo command
As we have seen, the echo command is used to print out a specified message in the terminal, here is an
example:

The shell program above will print out the following output:

Variables in shell programming


Variables are the building blocks of any program, they store a value, and you can even tinker with this value
at any time. Assigning a value is extremely easy in shell programming, in fact so easy that you don’t even
have to initialize them like in C programming language.
To assign a variable simply follow the syntax shown below:
<varianle name> = <value>
And when you take up the name of this variable in any other parts of your program, be sure to use the dollar
sign before it
For example, in the program shown below the value of x is 10 and it is later printed using the echo command
(note the dollar sign before ‘x’):

You can even print some text before the number to give a better understanding of the output as shown:

We can also create string variables in the same way:

We can create many variables like float, integers, strings and so many more in a similar fashion.
When we speak of variables, we also talk about the predefined variables in the system called the
“environmental variables”. We can also print these variables by incorporating them into our program, here is
an example:
The command above prints the environmental variables BASH, USERNAME, HOME, and PWD and I did
not even assign them:

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:

You can also read strings in the same way:


In the shell program shown above, the user is asked for their first name and last name, these values are
stored into the variables “a” and “b” respectively, then both the variables were printed one after the other.

Expressions in shell programming


Now that we have learned how to deal with variables and how to read the input from users, let us now
understand how expressions work in shell programming. Here they are not as simple as writing “2+3”,
instead, you have to make use of the keyword “`expr”
You can even save an expression in a variable and access it later as shown:

Similarly, you can even operate on variables as shown below:


And upon running the above code, we get the following output:

Operators in shell programming


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 (\*)
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:

The relational operators are:


1. Greater than (-gt)
2. Less than (-lt)
3. greater than or equal to (-ge)
4. Less than or equal to (-le)
5. Equal to (-eq)
6. Not equal to (-ne)
The logical operators are:
1. Logical and (&&)
2. Logical or (||)
3. Not equal to (!)
We will look at examples of these when using loops in shell programming.
“If -else” statement in shell programming
Just like every other programming language, shell programming also had lupus and if-else statements. Let us
first look at the syntax of the if-else statements:
1. “if … then” statement
If <condition>;
then
<arguments>
Fi

Upon executing the program shown above, we get the following output:

2. “if … then … else” statement


If <condition>
Then
<arguments>
Else
<arguments>
Fi
The above program will give the following output:

3. “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:

4. Nested if
We can also nest one if loop inside another if loop, to further narrow down the condition, the following is a
really beautiful example that illustrated if loops using all of the information we learned till now like
environment variables, logical operators, nested if, else, comments and more:

Upon executing the program shown above, we get the following output:

Switch case in shell programming


In shell programming, we can use multiple if-else statements, but this is not the best solution when all of the
branches depend on the value of a single variable.
In such cases, we use “case”. In shell programming Just like if-else statements, we have switch-esac
statements. Before we see an example, let us look at how it works.
The case statement is given an expression to evaluate and several different statements to execute based on
the value of the expression. The program checks each case against the value of the expression until a match
is found, if it all a match is not found, it simply exits without performing any action.
The following is the syntax followed while writing case statements:
case word in
pattern1)
Statement(s) to be executed if pattern1 matches
;;
pattern2)
Statement(s) to be executed if pattern2 matches
;;
pattern3)
Statement(s) to be executed if pattern3 matches
;;
*)
Default condition to be executed
;;
esac
Now, let us look at an example of the case statement in action:

The output of the above-shown shell program will be:


Loops in shell programming
Just like every other programming language, shell programming also has loops, namely for loop, while loop,
and do-while loop. Before we look at some examples of each let us look at the difference between while
loop and do while loop.
The while loop checks the condition first and executes a set of commands while it is true, 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.
For loop:

The output of the above-shown shell program will be:

While loop:

The output of the above-shown shell program will be:


Do while loop:

The output of the above-shown shell program will be:


Ex – 8: Study and practice on awk with relevant commands, syntax, usage and applications.
AWK Command
The awk command is used for text processing in Linux. Although, the sed command is also used for text
processing, but it has some limitations, so the awk command becomes a handy option for text processing. It
provides powerful control to the data.
The Awk is a powerful scripting language used for text scripting. It searches and replaces the texts and sorts,
validates, and indexes the database.
It is one of the most widely used tools for the programmer, as they write the scaled-down effective program
in the form of a statement to define the text patterns and designs.
It acts as a filter in Linux. It is also referred as gawk (GNU awk) In Linux.
How is it named as AWK?
This command is named by using the first letter of the name of three people who wrote the original version of
this command in 1977. Their names are Alfred Aho, Peter Weinberger, and Brian Kernighan and they
were from AT & T Bell Laboratories.
Features of AWK command
Various features of the Awk command are as follows:
o It scans a file line by line.
o It splits a file into multiple fields.
o It compares the input text or a segment of a text file.
o It performs various actions on a file like searching a specified text and more.
o It formats the output lines.
o It performs arithmetic and string operations.
o It applies the conditions and loops on output.
o It transforms the files and data on a specified structure.
o It produces the format reports.
Syntax:
The Awk command is used as follows:

awk options 'selection _criteria {action }' input-file > output-file


The options can be:
o -f program files: It reads the source code of the script written on the awk command
o -F fs: It is used as the input field separator.
AWK program structure
The AWK program is a collection of the pairs of pattern actions, specified as:
condition {action}
condition {action}
...
How to define AWK Script?
To define the awk script, use the awk command followed by curly braces {} surrounded by single quotation
mark '' as follows:

awk '{ print "Welcome to Awk command"}'


The above command will print the inputted string every time we execute the command. Press CTRL+D key
to terminate the program. Consider the below output:

AWK Command Examples


To create data, execute the cat command as follows:

cat > student.txt


Sam CS
Daniel IT
John IT
Arya IT
Mike ECE
Helena ECE
Press CTRL + D key to save the file and ESC key to exit from the command-line editor. It will create data.
Consider the below output:

A student data has been created, and we will operate the awk command on this data.
Example1: List students with the specified pattern.
Consider the below command:

awk '/ CS/ {print} ' student.txt


Output:

Example2: Default behaviour of awk command.


If we do not specify the pattern, it will show all of the content of the file.
Consider the below command:

awk '{print}' student.txt


We have not specified any pattern in the above command so, it will display all lines of the file.
Output:

Example3: Print the specified column.


If we specify the column number on this command, it will print that line only. Consider the below output:

awk '{print $1,$5} student.txt


The above command will print the column number 1 and 5. If column 5 does not exist in the file system, it
will only print column number 1.
onsider the below output:
Ex – 9: Study and practice on regular expressions and the grep family with relevant commands,
syntax, usage and applications.
Linux Regular Expression
Regular expression is also called regex or regexp. It is a very powerful tool in Linux. Regular expression is a pattern
for a matching string that follows some pattern.
Regex can be used in a variety of programs like grep, sed, vi, bash, rename and many more.
Regular Expression Meta-characters
A regular expression may have one or several repeating meta-characters.

Meta-character Description

. Replaces any character.

^ Matches start of string and represents characters not in the string.

$ Matches end of string.

* Matches zero or more times the preceding character.

\ Represents the group of characters.

() Groups regular expressions.

? Matches exactly one character.

+ Matches one or more times the preceding character.

{N} Preceding character is matched exactly N times.

{N,} Preceding character is matched exactly N times or more.

{N,M} Preceding character is matched exactly N times, but not more than N times.

- Represents the range.

\b Matches empty string at the edge of a word.

\B Matches empty string if it is not at the edge of a word.

\< Matches empty string at the beginning of a word.


\> Matches empty string at the end of a word.

Regex Versions
There are three versions of regular expressions syntax:
o BRE : Basic Regular Expressions
o ERE : Extended Regular Expressions
o PRCE: Perl Regular Expressions
Depending on tool or programs, one or more of these versions can be used.
Linux grep Regular Expressions
The grep tool has the following options to use regular expressions:
o -E : String is read as ERE (Extended Regular Expressions)
o -G : String is read as BRE (Basic Regular Expressions)
o -P : String is read as PRCE (Perl Regular Expressions)
o -F : String is read literally.
Print Lines Matching A Pattern
The grep command will search for line that matches the specified pattern.
Syntax:
grep <pattern> <fileName>
Example:
grep t msg.txt
grep l msg.txt
grep v msg.txt

Look at the above snapshot, all the matching pattern lines are displayed and pattern is highlighted.
Concatenating Characters
If a pattern is of concatenating characters then it has to be matched as it is, for the line to be displayed.
Example:
grep tp msg.txt
grep in msg.txt
grep is msg.txt

Look at the above snapshot, lines matching exactly the specified patterns are displayed.
Separating Words
Syntax:
grep '\b<pattern>\b' <fileName>
Example:
grep '\bsome\b' file

Look at the above snapshot, by giving command "grep some file all the lines matching to the word 'some' are
displayed. But by giving command "grep '\bsome\b' file" only lines matching single word 'some' are
displayed.
Ex – 10: Study and practice on compilation process of C programs under UNIX.

C Programming language is a well-known programming language because of its rich library of functions. C program
does not execute without a compiler in Linux. Therefore a dedicated compiler is needed to compile programming
languages in Linux distribution.
How C Program is run in Linux
C program code is first compiled by a compiler which converts the strings-based code into machine code that can be
readable by a computer machine. In Linux, the most common compiler used for C programming is GCC compiler and
is available in the default repository of the many distributions of Linux that can be installed easily using the apt package
manager:
Why do We Need to Install the Build-Essential Package?

build-essential meta-package in Ubuntu comes with five separate packages, including the GCC Compiler, that are
required during a software compilation process, which will help compile a C program in Linux. All these five packages
are listed below:

 gcc: The GNU Compiler Collection (GCC Compiler) for compilation of programs written in C Language.
 g++ : The GNU C++ compiler for compilation of programs written in C++ Language.
 libc6-dev: This is the GNU library files package. The development libraries and header files needed to know
how to compile the C program in Linux are included in this package.
 make: This is a handy tool for controlling the compilation of programs. This tool reads a file called a "makefile",
which tells the compiler how to do its job.
 dpkg-dev: This package can be used to unzip, compile, and upload Debian source packages. This tool will come
in handy if you wish to package your program for a Debian-based system.

Once the GCC package has been installed, now it’s time to create a file using the nano editor with the name myfile.c,
(“.c” is the extension that tells the computer that this file contains a C program):

Write the simple code in the C language of printing “Hello Linux Hint! ”:
In the above code, we included a header file the stdio, which is used to include input and output related information,
the main () is the function of the program, printf is used to print the output, and return 0 is the exit status.
Press CTRL+S to save the file and exit the editor by pressing CTRL+X. List down the contents of the file by using the
ls command to verify the creation of the file:

The file is being successfully created, to compile the file using the GCC compiler, run the following command:

In the above command the gcc is the compiler that compiles the file which was created with the name of myfile.c and
then checks whether it has an error or not, and if there is no error, then the “myfile” (binary file) will be generated in
the same directory. To execute the binary file use:

In the above output, we have seen that the output of our C program has been displayed.

You might also like