Вы находитесь на странице: 1из 171

Introduction to Linux (CSP3213)

Program 1

Aim: Introduction: Linux Foundation, Linux Requirements , Linux Philosophy and


Components, Linux History, Linux Community, Linux Terminology, Linux Distributions.

Linux Foundation
Since its inception in 1991, Linux has grown to become a major force in computing.
The Linux Foundation is a nonprofit organization that sponsors the work of Linux
creator Linus Torvalds. It was founded in 2000 and its mission is to promote, protect, and
advance Linux. The Linux Foundation is supported by leading technology companies and
thousands of individual members from around the world and marshalls the resources of its
members and the open source development community to ensure that Linux remains free
and technically advanced.
The Linux Foundation is active on many fronts.
 Produces technical events throughout the world.

 Develops and delivers training programs.

 Hosts major collaborative projects and industry initiatives.

 Manages kernel.org where the official versions of the Linux kernel are released.

 Runs the popular website linux.com

Linux Foundation Events: The Linux Foundation hosts conferences and other events
throughout the world which bring community members together in person. These events:
 Provide an open forum for development of the next kernel release.

 Bring together developers and system administrators to solve problems in a real-


time environment.

 Host workgroups and community groups for active discussions.

 Connect end users, system administrators, and kernel developers in order to grow
Linux use in the enterprise.

 Encourage collaboration among the entire community.

 Provide an atmosphere that is unmatched in its ability to further the platform.

Linux Foundation Training: Build the critical skills that individuals and organizations need to
get the most out of Linux and continue with self-directed learning. It is for the community

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
Page |1
Introduction to Linux (CSP3213)
and is designed by members of the community. The System Administration courses focus on
Enterprise Linux environments and target system administrators, technical support, and
architects. The developer courses feature instructors and content straight from the leaders
of the Linux developer community. The training is distribution-flexible, technically advanced,
and created with the actual leaders of the Linux development community themselves.
Linux Distributions and Software Requirements
There are many distribution families and hundreds of distributions available. Families and
their distributions that are fairly widely used and are broadly representative of their
respective family are:
Debian Family Systems (such as Ubuntu)
SUSE Family Systems (such as openSUSE)
Fedora Family Systems (such as CentOS)

Fedora Family
Fedora is the community distribution that forms the basis of Red Hat Enterprise
Linux (RHEL), CentOS, Scientific Linux, and Oracle Linux .Fedora contains significantly more
software than Red Hat’s enterprise version. One reason for this is that a diverse community
is involved in building Fedora; it is not just a company.
Once installed, CentOS is also virtually identical to Red Hat Enterprise Linux, which is the
most popular Linux distribution in enterprise environments.
Key Facts of the Fedora Family
 The Fedora family is upstream for CentOS, RHEL, and Oracle Linux.

 The Linux kernel 2.6.32 is used in RHEL/CentOS 6.x

 It supports hardware platforms such as x86, x86-64, Itanium, PowerPC, and IBM
System z.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
Page |2
Introduction to Linux (CSP3213)
 It uses the RPM-based yum package manager (we cover in more detail later) to
install, update, and remove packages in the system.

 RHEL is widely used by enterprises which host their own systems.

SUSE Family
The relationship between SUSE, SUSE Linux Enterprise Server (SLES), and openSUSE is similar
to the one described between Fedora, Red Hat Enterprise Linux, and CentOS. In
this openSUSE 12.3 as the reference distribution for the SUSE family is available to end
users at no cost. The two products are extremely similar, and material that
covers openSUSE can typically be applied to SLES with no problem.
Key Facts About The SUSE Family
 SUSE Linux Enterprise Server (SLES) is upstream for openSUSE.

 The Linux kernel 3.11 is used in openSUSE 12.3.

 It uses the RPM-based zypper package manager (we cover in more detail later) to
install, update, and remove packages in the system.

 It includes the YaST (Yet another System Tool) application for system administration
purposes.

 SUSE is widely used in the retail sector.

Debian Family
The Debian distribution is upstream for several other distributions including Ubuntu, and
Ubuntu is upstream for Linux Mint and others. It is commonly used on both servers and
desktop computers. Debian is a pure open source project and focuses on one key aspect,
that is, stability. It also provides the largest and most complete software repository to its
users.
Ubuntu aims at providing a good compromise between long term stability and ease of use.
Since Ubuntu gets most of its packages from Debian’s stable branch, Ubuntu also has access
to a very large software repository.
Key Facts About the Debian Family
 The Debian family is upstream for Ubuntu, and Ubuntu is upstream for Linux
Mint and others.

 The Linux kernel 3.13 is used in Ubuntu 14.04.

 It uses the DPKG-based apt-get package manager (we cover in more detail later) to
install, update, and remove packages in the system.

 Ubuntu has been widely used for cloud deployments.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
Page |3
Introduction to Linux (CSP3213)
 Ubuntu is built on top of Debian, it uses the Unity graphical interface, is GNOME-
based and differs quite a bit visually from the interface on standard Debian as well as
other distributions.

While choosing a Linux distribution system, you will notice that the technical differences
are mainly about package management systems, software versions, and file locations. Once
you get a grasp of those differences it becomes relatively painless to switch from one Linux
distribution to another.

Linux History
Linux is a free open source computer operating system initially developed for Intel x86-
based personal computers. It has been subsequently ported to many other hardware
platforms. However Linux evolved from a student project into a massive effort with an
enormous impact on today's world.
Linus Torvalds was a student in Helsinki, Finland, in 1991 when he started a project: writing
his own operating system kernel. He also collected together and/or developed the other
essential ingredients required to construct an entire operating system with his kernel at the
center. This soon became known as the Linux kernel.
In 1992, Linux was re-licensed using the General Public License (GPL) by GNU (a project of
the Free Software Foundation (FSF) which promotes freely available software) which made
it possible to build a worldwide community of developers. By combining the kernel with
other system components from the GNU project, numerous other developers created
complete systems called Linux Distributions in the mid-90’s.
The Linux distributions created in the mid-90’s provided the basis for fully free computing
and became a driving force in the open source software movement. In 1998, major
companies likeIBM and Oracle announced support for the Linux platform and began major
development efforts as well.
Today, Linux powers more than half of the servers on the Internet, the majority of smart-
phones (via the Android system which is built on top of Linux), and nearly all of the world’s
most powerful supercomputers.

Linux Philosophy
Linux borrows heavily from the UNIX operating system because it was written to be a free
and open source version of UNIX. Files are stored in a hierarchical file system, with the top
node of the system being root or simply "/". Whenever possible, Linux makes its
components available via files or objects that look like files. Processes, devices, and network
sockets are all represented by file-like objects, and can often be worked with using the same
utilities used for regular files.
Linux is a fully multitasking (a method where multiple tasks are performed during the same
period of time), multiuser operating system, with built-in networking and service processes
known as daemons in the UNIX world.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
Page |4
Introduction to Linux (CSP3213)
Linux Community
The Linux community is a far-reaching ecosystem consisting of developers, system
administrators, users and vendors, who use many different forums to connect with one
another. Among the most popular are:
 Linux User Groups (both local and online)

 Internet Relay Chat (IRC) software (such as Pidgin and XChat)

 Online communities and discussion boards

 Newsgroups and mailing lists

 Community events (such as LinuxCon and ApacheCon)

One of the most powerful online user communities is linux.com. This site is hosted by
the Linux Foundation and serves over one million unique visitors every month. It has active
sections on:
 News

 Community discussion threads

 Free tutorials and user tips

Terminology
Kernel: Interface between the hardware and the user applications. It is the core part of the
system.
Distribution: Collection of software making up a Linux-based OS.
Boot Loader: Program that boots the operating system.
Service: Program that runs as a background process.
File system: Method for storing and organizing files.
X window System: Toolkit for developing graphical subsystem on nearly all linux systems.
Desktop Environment: GUI on top of the operating system.
Command Line: Interface for typing commands on top of the OS.
Shell: Command line interpreter that interprets the commands and instructs the kernel to
perform required tasks and commands.

Linux distributions
Linux kernel is the core of a computer operating system. A full Linux distribution consists of
the kernel plus a number of other software tools for file-related operations, user
management, and software package management. Each of these tools provides a small part
of the complete system. Each tool is often its own separate project, with its own developers
working to perfect that piece of the system.

Examples of other essential tools and ingredients provided by distributions include


the C/C++ compiler, the gdb debugger, the core system libraries applications need to link

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
Page |5
Introduction to Linux (CSP3213)
with in order to run, the low-level interface for drawing graphics on the screen as well as the
higher-level desktop environment, and the system for installing and updating the various
components including the kernel itself.

Services Associated with Distributions

A vast variety of Linux distributions cater to different audiences and organizations


depending on their specific needs. Large commercial organizations tend to favor the
commercially supported distributions from Red Hat, SUSE and Canonical (Ubuntu).
CentOS is a popular free alternative to Red Hat Enterprise Linux
(RHEL). Ubuntu and Fedora are popular in the educational realm. Scientific Linux is favored
by the scientific research community for its compatibility with scientific and mathematical
software packages. Both CentOS and Scientific Linux are binary-compatible with RHEL; i.e.,
binary software packages in most cases will install properly across the distributions.
Many commercial distributors, including Red Hat, Ubuntu, SUSE, and Oracle, provide long
term fee-based support for their distributions, as well as hardware and software

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
Page |6
Introduction to Linux (CSP3213)
certification. All major distributors provide update services for keeping your system primed
with the latest security and bug fixes, and performance enhancements, as well as provide
online support resources.

Learning Outcome: This experiment will introduce the students to LINUX Operating system,
its terminology, philosophy and various distribution families and their distributions.

Viva Questions

 Name some of the distribution families available.


 Give the software requirements for installation of Ubuntu.
 What is Linux Foundation?
 What is a boot Loader?
 What do you mean by Kernel and Shell?
 Red hat linux belongs to which family?
 Ubuntu linux belongs to which family?
 What is the purpose of linux foundation?
 What kind of events is held by linux foundation?
 What do you mean by platform independence?

ACTIVITY FOR THE STUDENTS

Briefly describe why Ubuntu is suitable distribution for installation in your practice labs?

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
Page |7
Introduction to Linux (CSP3213)
Program 2

Aim: Installation: Configuration and Customizations of Unix/Linux, Linux Structure and


Installation.

Steps for installing Red Hat Linux 5.

Step 1: Select and insert the media that you’ll use to boot the Red Hat Enterprise Linux 5
installation program. It can be the first Red Hat Enterprise Linux 5 CD, a boot CD created
from the boot.iso file from the /images directory of the first installation CD, or a boot USB
key created from the diskboot.img file from the same directory.

Step 2: Power on your system. Press the appropriate key, typically ESC, F12, or DEL, to
access the boot menu shown here. If a boot menu isn’t available, you’ll need to adjust the
boot sequence in the computer BIOS, which you can then use to boot directly from your
selected media. Set your computer’s BIOS to boot from the first installation CD or USB
drive. Details vary by PC. Make sure your BIOS saves your changes before you reboot.

Step 3: Type linux askmethod when you see the boot: prompt. Graphical Installation ,
Choose a language and select OK. Select a keyboard and select OK. Select CD Rom and
select OK. If you don’t have an installation number, select the Skip Entering Installation
Number radio button.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
Page |8
Introduction to Linux (CSP3213)

Step 4: If there are existing partitions on the installed hard drives, you’ll get the chance to
confirm that you want to remove said partitions (this step isn’t final). If you’re configuring a
dual-boot with another operating system, don’t delete the partitions! Instead, click Back and
select Create A Custom Layout. However, dual-boot configuration, especially with Microsoft
Windows, is preferable.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
Page |9
Introduction to Linux (CSP3213)

Step 5: Set the time zone for your system. If you don’t have another operating system on this
computer, keep the System Clock Uses UTC option active. Then click Next.

Step 6: Type in and confirm the root password for your system. Click Next.

Step 7: There are two package customization screens available. Everyone sees the screen
shown next. (The choices are slightly different for Red Hat Enterprise Linux 5 Client.) You
can accept the defaults, select available options, and/or select Customize Now. It’s usually
best to customize modestly (I’ve selected the Customize Now option), based on the
requirements on your particular Installation and Configuration exam. Click Next. (If you
don’t select Customize Now, skip the next step.).

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 10
Introduction to Linux (CSP3213)

Step 8: The next screen congratulates you for completing the installation. The next step is to
reboot your computer into RHEL. Click Reboot.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 11
Introduction to Linux (CSP3213)

Learning Outcome:
Unix/Linux and customizations and configurations are learned.

Viva questions

 What is the command gunzip used for?


 What is intramfs?
 What is GRUB2 boot Loader?
 What is the command chmod used for?
 What does UID stand for?
 What do you mean by root?
 What do you mean by a superuser?
 What is boot loader?
 What do you mean by boot program?
 What is the first process initialized by the boot loader?

ACTIVITY FOR THE STUDENTS

Give the customizations and configurations for one more distribution form fedora family.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 12
Introduction to Linux (CSP3213)
Program 3
Aim: Installation: Linux file-system basics, the boot process, Linux Distributions

Installation
File system, is the embodiment of a method of storing and organizing arbitrary collections of
data in a human-usable form.

Different Types of File systems Supported by Linux:


 Conventional disk file systems: ext2, ext3, ext4, XFS, Btrfs, JFS, NTFS, etc.

 Flash storage file systems: ubifs, JFFS2, YAFFS, etc.

 Database file systems

 Special purpose files systems: procfs, sysfs, tmpfs, debugfs, etc.

Partitions and File systems


A partition is a logical part of the disk, whereas a filesystem is a method of storing/finding
files on a hard disk (usually in a partition). By way of analogy, you can think of filesystems as
being like family trees that show descendants and their relationships, while the partitions
are like different families (each of which has its own tree).
A comparison between filesystems in Windows and Linux is given in the following table:

Windows Linux

Partition Disk1 /dev/sda1

Filesystem type NTFS/FAT32 EXT3/EXT4/XFS...

Mounting DriveLetter MountPoint


Parameters

Base Folder where C drive /


OS is stored

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 13
Introduction to Linux (CSP3213)

The File System Hierarchy Standard


Linux systems store their important files according to a standard layout called the Filesystem
Hierarchy Standard, or FHS.
This standard ensures that users can move between distributions without having to re-learn
how the system is organized. Linux uses the ‘/’ character to separate paths (unlike Windows,
which uses ‘\’), and does not have drive letters. New drives are mounted as directories in
the single filesystem, often under /media.
All Linux filesystem names are case-sensitive, so /boot, /Boot, and /BOOT represent three
different directories (or folders). Many distributions distinguish between core utilities
needed for proper system operation and other programs, and place the latter in directories
under /usr (think "user").

The Boot Process


The Linux boot process is the procedure for initializing the system. It consists of everything
that happens from when the computer power is first switched on until the user interface is
fully operational.
Once you start using Linux, you will find that having a good understanding of the steps in the
boot process will help you with troubleshooting problems as well as with tailoring the
computer's performance to your needs.

BIOS
Starting an x86-based Linux system involves a number of steps. When the computer is
powered on, the Basic Input/Output System (BIOS) initializes the hardware, including the
screen and keyboard, and tests the main memory. This process is also called POST (Power
On Self Test).
The BIOS software is stored on a ROM chip on the motherboard. After this, the remainder of
the boot process is completely controlled by the operating system.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 14
Introduction to Linux (CSP3213)

Fig:Boot Process

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 15
Introduction to Linux (CSP3213)

Linux Distribution Installation


A partition layout needs to be decided at the time of installation because Linux systems
handle partitions by mounting them at specific points in the filesystem. You can always
modify the design later, but it always easier to try and get it right to begin with.
Nearly all installers provide a reasonable filesystem layout by default, with either all space
dedicated to normal files on one big partition and a smaller swap partition, or with separate
partitions for some space-sensitive areas like /home and /var. You may need to override the
defaults and do something different if you have special needs, or if you want to use more
than one disk.
All installations include the bare minimum software for running a Linux distribution.
Most installers also provide options for adding categories of software. Common applications
(such as the Firefox web browser and LibreOffice office suite), developer tools (like
the vi and emacs text editors which we will explore later in this course), and other popular
services, (such as the Apache web server tools or MySQLdatabase) are usually included. In
addition, a desktop environment is installed by default.
All installers secure the system being installed as part of the installation. Usually, this
consists of setting the password for the superuser (root) and setting up an initial user. In
some cases (such as Ubuntu), only an initial user is set up; direct root login is disabled and
root access requires logging in first as a normal user and then using sudo as we will describe
later. Some distributions will also install more advanced security frameworks, such
as SELinux or AppArmor.

1. Linux Installation: Install Source

Like other operating systems, Linux distributions are provided on optical media such as CDs
or DVDs. USB media is also a popular option. Most Linux distributions support booting a
small image and downloading the rest of the system over the network; these small images
are usable on media or as network boot images, making it possible to install without any
local media at all.
Many installers can do an installation completely automatically, using a configuration file to
specify installation options. This file is called a Kickstart file for Fedora-based systems,
anAutoYAST profile for SUSE-based systems, and a preseed filefor the Debian-based
systems.

2. Linux Installation: The Process

Each distribution provides its own documentation and tools for creating and managing
these files.
The actual installation process is pretty similar for all distributions.
After booting from the installation media, the installer starts and asks questions about how
the system should be set up. (These questions are skipped if an automatic installation file is
provided.) Then, the installation is performed.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 16
Introduction to Linux (CSP3213)
Finally, the computer reboots into the newly-installed system. On some distributions,
additional questions are asked after the system reboots.
Most installers have the option of downloading and installing updates as part of the
installation process; this requires Internet access. Otherwise, the system uses its normal
update mechanism to retrieve those updates after the installation is done.

Learning Outcomes:
 Identify Linux file systems.

 Identify the differences between partitions and file systems.

Viva Questions

 Define BIOS
 What do you mean by POST?
 What is the first sector of Hard disk known as?
 Why is boot program always stored on a firmware?
 Identify Linux file systems.
 Identify the differences between partitions and file systems.
 Describe the boot process.
 Know how to install Linux on a computer.
 Name different flash storage file systems?
 Name different database file systems?
 Name conventional file systems?

Activity for the students

Install Ubuntu on your personal laptops.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 17
Introduction to Linux (CSP3213)

Program 4:

Aim: Introduction to gcc compiler: Compilation Of Program, Execution Of Program

History
The original author of the GNU C Compiler (GCC) is Richard Stallman, the founder of the
GNU Project. The GNU Project was started in 1984 to create a complete Unix-like operating
system as free software.
The first release of GCC was made in 1987. This was a significant breakthrough, being the
first portable ANSI C optimizing compiler released as free software. Since that time GCC has
become one of the most important tools in the development of free software.
Over time GCC has been extended to support many additional languages, including Fortran,
ADA, Java and Objective-C. The acronym GCC is now used to refer to the "GNU Compiler
Collection". Its development is guided by the GCC Steering Committee, a group composed of
representatives from GCC user communities in industry, research and academia.

Features of GCC:
1. GCC is a portable compiler--it runs on most platforms available today, and can produce
output for many types of processors. In addition to the processors used in personal
computers, it also supports microcontrollers, DSPs and 64-bit CPUs.
2. GCC is not only a native compiler--it can also cross-compile any program, producing
executable files for a different system from the one used by GCC itself. This allows software
to be compiled for embedded systems which are not capable of running a compiler. GCC is
written in C with a strong focus on portability, and can compile itself, so it can be adapted to
new systems easily.
3. GCC has multiple language frontends, for parsing different languages. Programs in each
language can be compiled, or cross-compiled, for any architecture. For example, an ADA
program can be compiled for a microcontroller, or a C program for a supercomputer.
4. GCC has a modular design, allowing support for new languages and architectures to be
added. Adding a new language front-end to GCC enables the use of that language on any
architecture, provided that the necessary run-time facilities (such as libraries) are available.
Similarly, adding support for a new architecture makes it available to all languages.
5. GCC is free software, distributed under the GNU General Public License (GNU GPL).(1) This
means you have the freedom to use and to modify GCC, as with all GNU software. If you
need support for a new type of CPU, a new language, or a new feature you can add it
yourself, or hire someone to enhance GCC for you. You can hire someone to fix a bug if it is
important for your work.
Introduction to commands in gcc compiler and shell programming

There are two methods for creating a file.


$cat>filename
(Type contents into your file and press (control+D) for saving and quitting the file).
Vi Editor(explain vi editor basic commands that are required to write a program )

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 18
Introduction to Linux (CSP3213)
$vi filename(Type contents into your file and press (Esc + :wq) for saving and quitting the
file.

How to write a program in GCC compiler in Linux:


$vi filename.c
#include<stdio.h>
Void main()
{
Printf(“hello”);
}
Press esc ,then :wq for saving and quitting from the file.
Note: Students can also write the program in gedit too.
How to compile a program in gcc:
$ gcc filename.c (this command will compile your file and show errors if any.)
How to run a program in gcc:
$ ./a.out (this command will execute your file and display the output ‘hello’ on screen)

Learning Outcome:
 Compilation of program in gcc compiler

 Execution of program in gcc compiler.

Viva Questions

 What are compilers?


 How are compilers different from interpreters?
 Why do you need to compile a file?
 File with what extension is created after compilation?
 Why are compilers preferred over shell?
 How do you compile a program with cc compiler?
 How do you execute a program with gcc compiler?
 Give the command to save a file using vi editor?
 How is gedit different from vi editor?

ACTIVITY FOR THE STUDENTS

Write a program to print your name and compile and execute the program using gcc
compiler.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 19
Introduction to Linux (CSP3213)
Program 5:

Study basic and user status Unix/Linux Commands: man, help, history, who, whoami, id,
uname, tty, usermod

1. Man: Browsing the manual pages online

It is an online help facility; man displays the documentation, called man documentation of
practically every command in the system.

Syntax: man <command name>

A man page is divided into a number of mandatory and optional sections, of which three are
always there Name, Synopsis, and Description.
Name: One-line introduction to the command.
Synopsis: Syntax used by the command.
Description: Provides details related to the command.

Synopsis:
If a command argument is enclosed in rectangular brackets, then it is optional; otherwise,
the argument is required.
The ellipsis implies that there can be more instances of the preceding word.
If there is a | character in any of the areas, it means that only one of the options shown on
the either side of the pipe can be used.

EXIT STATUS:
Exit status list possible error conditions and their numeric representations.

man –k prints a one-line description of the command.

2. help
bash has a built-in help facility available for each of the shell built-ins. To use it, type “help”
followed by the name of the shell built-in or, you may add the -m option to change the
format of the output.

--help
Many executable programs support a “--help” option that displays a description of the
command's supported syntax and options.

3. History: Executing command from terminal will show you a complete list of last executed
commands with line numbers.
With ‘export’ command with variable will display history command with corresponding
timestamp when the command was executed.
$ export HISTTIMEFORMAT='%F %T '

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 20
Introduction to Linux (CSP3213)
Use the following ‘export‘ command by specifying command in HISTIGNORE=’ls -
l:pwd:date:’ will not saved by system and not be shown in history command.
$ export HISTIGNORE='ls -l:pwd:date:'
With the below command will help us to ignore duplicate commands entry made by user.
Only single entry will be shown in history, if a user executes a same command multiple
times in a Bash Prompt.
$ export HISTCONTROL=ignoredups

4. who: who Displays who is on the system.

Synopsis: who [OPTION]... [ FILE | ARG1 ARG2 ]


-b, --boot
time of last system boot

-q, --count
all login names and number of users logged on

-s, --short
print only name, line, and time (default)

-t, --time
print last system clock change

-T, -w, --mesg


add user's message status as +, - or ?

-u, --users
list users logged in

--message
same as -T

--version
output version information and exit

5. who am i: Displays the invoking user.

6. id - print real and effective UIDs and GIDs

Synopsis
id [OPTION]... [USERNAME]

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 21
Introduction to Linux (CSP3213)
Description:

Print information for USERNAME, or the current user.


-a
ignore, for compatibility with other versions
-g, --group
print only the effective group ID
-G, --groups
print all group IDs
-n, --name
print a name instead of a number, for –ugG
-u, --user
print only the effective user ID

7. tty: Displays users terminal name

8. uname: print system information

Synopsis:
uname [OPTION]...

Description:
Print certain system information. With no OPTION, it is the same as -s.
-a, --all
print all information, in the following order:
-s, --kernel-name
print the kernel name
-n, --nodename
print the network node hostname
-r, --kernel-release
print the kernel release
-v, --kernel-version
print the kernel version
-m, --machine
print the machine hardware name
-p, --processor
print the processor type
-i, --hardware-platform
print the hardware platform
-o, --operating-system
print the operating system
--help
display this help and exit

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 22
Introduction to Linux (CSP3213)
--version
output version information and exit

9. usermod: used to modify or change any attributes of a already created user account via
command line.
Options:
-c: We can add comment field for the user account.
-d: To modify the directory for an existing user account.
-e: Using this option we can make the account expiry in specific period.
-g: Change the primary group for a User.
-G: To add a supplementary groups.
-a: To add anyone of the group to a secondary group.
-l: To change the login name from tecmint to tecmint_admin.
-L: To lock the user account. This will lock the password so we can’t use the account.
-m: moving the contents of the home directory from existing home dir to new dir.
-p:To Use un-encrypted password for the new password. (NOT Secured).
-s: Create a Specified shell for new accounts.
-u: Used to Assigned UID for the user account between 0 to 999.
-U: To unlock the user accounts. This will remove the password lock and allow us to use the
user account.

Learning Outcome:

Basic linux commands, were learned.

Viva Questions

 Give the command to display your terminal name.


 What are man pages?
 Give the command to display the time of last system boot.
 Print the effective UIDs and GIDs
 What do you mean by UIDs?
 What do you mean by GIDs?
 Give the command and option to change the login name?
 Give the command to modify the directory for an existing user account?
 Give the range for UID acoounts?

Activity to be performed

Access the man pages and practice all the options for all the commands you have learned in
this program.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 23
Introduction to Linux (CSP3213)
Program 6:

Aim: System Configuration from the Graphical Interface: System, Display, Time and Date
Settings, Network Manager, Installing and Updating Software.

System Settings:

The System Settings panel allows you to control most of the basic configuration options and
desktop settings such as specifying the screen resolution, managing network connections, or
changing the date and time of the system.

The procedure to access System Settings varies according to distribution:

- CentOS: click System → Preferences.

- openSUSE: click Activities, type Settings in the Search box.

- Ubuntu: they are located in the panel on the left of the screen.

System Display

The Displays panel under System Settings contains the most common settings for
changing the desktop appearance. These settings function independently of the specific
display drivers you are running.

If your system uses a proprietary driver such as those from nVidia or AMD, you will probably
have a configuration program for that driver that is not included in System Settings. This
program may give more configuration options, but may also be more complicated, and
might require sysadmin (root) access. If possible, you should configure the settings in
the Displays panel rather than the proprietary configuration program.

The X server, which actually provides the GUI, uses the /etc/X11/xorg.conf file as its
configuration file if it exists. In modern Linux distributions, this file is usually present only in
unusual circumstances, such as when certain less common graphic drivers are in use.
Changing this configuration file directly is usually for more advanced users.

Date and Time settings

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 24
Introduction to Linux (CSP3213)
Linux always uses Coordinated Universal Time (UTC) for its own internal time-keeping.
Displayed or stored time values rely on the system time zone setting to get the proper time.
UTC is similar to, but more accurate than, Greenwich Mean Time (GMT).

The Date and Time Settings window can be accessed from the System Settings window.
Alternatively, you can right-click Date and Time on the top panel to access the Date and
Time Settings window.

The Network Time Protocol (NTP) is the most popular and reliable protocol for setting the
local time via Internet servers. Most Linux distributions include a working NTP setup which
refers to specific time servers run by the distribution. This means that no setup, beyond "on
or off", is required for network time synchronization. If desired, more detailed configuration
is possible by editing the standard NTP configuration file (/etc/ntp.conf) for Linux NTP
utilities.

Network Manager:

All Linux distributions have network configuration files, but file formats and locations can
differ from one distribution to another. Hand editing of these files can handle quite
complicated setups, but is not very dynamic or easy to learn and use. The Network
Manager utility was developed to make things easier and more uniform across distributions.
It can list all available networks (both wired and wireless), allow the choice of a wired,
wireless or mobile broadband network, handle passwords, and set up Virtual Private
Networks (VPNs). Except for unusual situations, it’s generally best to let the Network
Manager establish your connections and keep track of your settings.

Configuring wireless connections in Ubuntu:

To configure Wireless Network in Ubuntu:

1. In top panel, click Network Manager.

2. Click Enable Wi-Fi - to display a list available Wireless Networks.

3. Click the desired Wireless Network.

4. For a secured network, enter the password.

5. To modify saved wireless network settings, click Edit Connections.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 25
Introduction to Linux (CSP3213)

Installing and Updating Software

Each package in a Linux distribution provides one piece of the system, such as the
Linux kernel, the C compiler, the shared software code for interacting with USB devices, or
the Firefox web browser.

Packages often depend on each other; for example, because Firefox can communicate using
SSL/TLS, it will depend on a package which provides the ability to encrypt and decrypt SSL
and TLS communication, and will not install unless that package is also installed at the same
time.

One utility handles the low-level details of unpacking a package and putting the pieces in
the right places. Most of the time, you will be working with a higher-level utility which
knows how to download packages from the Internet and can manage dependencies and
groups for you.

Let’s look at Package Management in the Debian Family System.

dpkg is the underlying package manager for these systems; it can install, remove, and build
packages. Unlike higher-level package management systems, it does not automatically
download and install packages and satisfy their dependencies.

For Debian-based systems, the higher-level package management system is


the apt(Advanced Package Tool) system of utilities. Generally, while each distribution within
the Debian family uses apt, it creates its own user interface on top of it (for example,apt-
get, aptitude, synaptic, Ubuntu Software Center, Update Manager, etc).
Although apt repositories are generally compatible with each other, the software they
contain generally isn’t. Therefore, most apt repositories target a particular distribution
(like Ubuntu), and often software distributors ship with multiple repositories to support
multiple distributions.

Steps:

1. Click on the Ubuntu icon in the left pane.

2. Type software in the search panel.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 26
Introduction to Linux (CSP3213)
3. Click on Ubuntu Software center.

4. In the upper right corner, type gpm in search box.

5. Click on the software and install.

6. To remove, click on remove.

Learning Outcome:

 Apply system, display, and date and time settings using the System Settings panel.

 Track the network settings and manage connections using Network Manager in Linux.

 Install and update software in Linux from a graphical interface.

VIVA QUESTIONS

 What is network manager?


 What is dpkg?
 Give steps to install the software.
 Give steps to update the software
 Give steps to remove the software.
 Give the steps to track the network settings?
 What is the purpose of network manager?
 What are the operations performed by dpkg?
 What is the full form of apt?

ACTIVITY FOR STUDENTS

 Practice the exercise given in your MOOC course (edx.org)

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 27
Introduction to Linux (CSP3213)
Program7

Aim: Command-line Operations: Command Line Mode Options, Basic Operations,


Installing Software, terminals, types of terminals, switching between terminals.

Introduction to the Command Line

Linux system administrators spend a significant amount of their time at a command


line prompt. They often automate and troubleshoot tasks in this text environment. There is
a saying, "graphical user interfaces make easy tasks easier, while command line interfaces
make difficult tasks possible." Linux relies heavily on the abundance of command line tools.
The command line interface provides the following advantages:

 No GUI overhead.

 Virtually every task can be accomplished using the command line.

 You can script tasks and series of procedures.

 You can log on remotely to networked machines anywhere on the Internet.

 You can initiate graphical apps directly from the command line.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 28
Introduction to Linux (CSP3213)
Using a Text Terminal on the Graphical Desktop

A terminal emulator program emulates (simulates)


a standalone terminal within a window on the
desktop. By this we mean it behaves essentially as if
you were logging into the machine at a pure text
terminal with no running graphical interface. Most
terminal emulator programs support multiple
terminal sessions by opening additional tabs or
windows.

By default, on GNOME desktop environments,


the gnome-terminalapplication is used to emulate a text-mode terminal in a window. Other
available terminal programs include:

 xterm

 rxvt

 konsole

 terminator
Launching Terminal Windows

To open a terminal in CentOS:

1) On the CentOS desktop, in the


upper-left corner, click
Applications.

2) From the System Tools menu,


select Terminal.

To open a terminal in openSUSE:

1) On the openSUSE desktop, in the


upper-left corner of the screen, click Activities.

2) From the left pane, click Show Applications.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 29
Introduction to Linux (CSP3213)
3) Scroll-down and select the required terminal.

To open a terminal in Ubuntu:

1) In the left panel, click the Ubuntu icon.

2) Type terminal in the Search box.

If the nautilus-open-terminal package is installed on any of these distributions, you can


always open a terminal by right clicking anywhere on the desktop background and
selecting Open in Terminal.

The X Window System

The customizable nature of Linux


allows you to drop (temporarily or
permanently) the X Window graphical
interface, or to start it up after the
system has been running. Certain
Linux distributions distinguish versions
of the install media between desktop
(with X) and server (usually without X);
Linux production servers are usually
installed without X and even if it is
installed, usually do not launch it
during system start up.

Removing X from a production server can be very


helpful in maintaining a lean system which can be
easier to support and keep secure.

Virtual Terminals

Virtual Terminals (VT) is console sessions that use


the entire display and keyboard outside of a
graphical environment. Such terminals are
considered "virtual" because although there can be

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 30
Introduction to Linux (CSP3213)
multiple active terminals, only one terminal remains visible at a time. A VT is not quite the
same as a command line terminal window; you can have many of those visible at once on a
graphical desktop.

One virtual terminal (usually number one or seven) is reserved for the graphical
environment, and text logins are enabled on the unused VTs.Ubuntu uses VT 7,
but CentOS/RHEL andopenSUSE use VT 1 for the graphical display.

An example of a situation where using the VTs is helpful when you run into problems with
the graphical desktop. In this situation, you can switch to one of the text VTs and
troubleshoot.

To switch between the VTs, press CTRL-ALT-corresponding function key for the VT. For
example, press CTRL-ALT-F6 for VT 6. (Actually you only have to press ALT-F6 key
combination if you are in a VT not running X and want to switch to another VT.)

The Command Line

Most input lines entered at the shell prompt have three basic elements:

 Command

 Options

 Arguments

The command is the name of the program you are executing. It may be followed by one or
more options (or switches) that modify what the command may do. Options usually start
with one or two dashes, for example,-p or--print, in order to differentiate them
from arguments, which represent what the command operates on.

However, plenty of commands have no options, no arguments, or neither. You can also type
other things at the command line besides issuing commands, such as setting environment
variables.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 31
Introduction to Linux (CSP3213)
Basic Operations

In this section we will


discuss how to accomplish
basic operations from the
command line. These
include how to log in and
log out from the system,
restart or shutdown the
system, locate
applications, access
directories, identify the
absolute and relative
paths, and explore the
filesystem.

Rebooting and Shutting Down

The preferred method to shut down or


reboot the system is to use
the shutdown command. This sends a
warning message and then prevents
further users from logging in.
The init process will then control shutting
down or rebooting the system. It is
important to always shut down properly;
failure to do so can result in damage to
the system and/or loss of data.

The halt and poweroff commands


issue shutdown -h to halt the
system; reboot issues shutdown -r and causes the machine to reboot instead of just shutting
down. Both rebooting and shutting down from the command line requires superuser (root)
access.

When administering a multiuser system, you have the option of notifying all users prior to
shutdown as in:

$ sudo shutdown -h 10:00 "Shutting down for scheduled maintenance."

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 32
Introduction to Linux (CSP3213)

Locating Applications

Depending on the specifics of your


particular distribution's policy, programs
and software packages can be installed in
various directories. In general, executable
programs should live in
the/bin, /usr/bin,/sbin,/usr/sbin directori
es or under /opt.

One way to locate programs is to employ


the which utility. For example, to find out
exactly where the diff program resides
on the filesystem:

$ which diff
If which does not find the program, whereis is a good alternative because it looks for
packages in a broader range of system directories:

$ whereis diff

Package Management Systems on Linux

The core parts of a Linux distribution and most of its add-on software are installed via
the Package Management System. Each package contains the files and other instructions
needed to make one software component work on the system. Packages can depend on
each other. For example, a package for a Web-based application written in PHP can depend
on the PHP package.

There are two broad families of package managers: those based on Debian and those which
use RPM as their low-level package manager. The two systems are incompatible, but
provide the same features at a broad level.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 33
Introduction to Linux (CSP3213)
Package Managers: Two
Levels

Both package
management systems
provide two tool levels: a
low-level tool (such
as dpkg or rpm), takes
care of the details of
unpacking individual
packages, running
scripts, getting the
software installed
correctly, while a high-
level tool (such as apt-
get, yum, or zypper)
works with groups of
packages, downloads packages from the vendor, and figures out dependencies.

Most of the time users need work only with the high-level tool, which will take care of
calling the low-level tool as needed. Dependency tracking is a particularly important feature
of the high-level tool, as it handles the details of finding and installing each dependency for
you. Be careful, however, as installing a single package could result in many dozens or even
hundreds of dependent packages being installed.

Working With Different Package Management Systems

 Advanced Packaging Tool (apt) is the underlying package management system that
manages software on Debian-based systems. While it forms the backend for
graphical package managers, such as the Ubuntu Software Center and synaptic, its
native user interface is at the command line, with programs that include apt-
get and apt-cache.

 The Yellowdog Updater Modified (yum) is an open-source command-line package-


management utility for RPM-compatible Linux systems, basically what we have
called the Fedora family. yum has both command line and graphical user interfaces

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 34
Introduction to Linux (CSP3213)

 .zypper is a package management system for openSUSE that is based on


RPM. zypper also allows you to manage repositories from the command
line. zypper is fairly straightforward to use and resembles yum quite closely.

Learning Outcome:

Learned using command line for the purpose we used GUI in Program 6

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 35
Introduction to Linux (CSP3213)

Viva Questions

 What is zypper?
 What is yum?
 Show all available packages.
 Give the full form for apt.
 Give command to install a package?
 Give command to update a package?
 Give command to remove a package?
 Give command to remove package dependencies?

ACTIVITY FOR THE STUDENTS

Differentiate between apt, yum and zipper

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 36
Introduction to Linux (CSP3213)
Program 8:

Aim: Working with Files: cat, cp, mv, rm

File oriented commands

1) cat-It issued to create a file, copy, display contents and concatenating two files.
Syntax: cat filename
$cat>filename
$ cat> f1 // Creates file f1
$ cat f1 // Displays contents of file f1
$ cat f1>f2 // Copies contents of f1 to f2
$ cat f1 f2>f3 // concatenates contents of fi and f2 to file f3
2. cp - to copy the contents of one file to another file.

Syntax- cp source filename target filename


$ cp f1 f2 // copies file f1 to f2

3. mv- move contents of one file to another.


Syntax- mv source filename target filename

4. rm- Remove files.


Syntax: rm [options] <filname>

Learning Outcome:

Basic commands related to files were learned.

Viva Questions
 Copy the contents of file abc ti file xyz
 Create a file by your name and file should contain you personal information
 Remove the file abc?
 What is cp command used for?
 What is the command for renaming?
 What is the purpose of rm command?
 Rename a file f1 to f1.c.
 What functions are performed using cat command

ACTIVITY FOR THE STUDENTS:

Create a file by your name and the file should contain your name, ID and section, copy the
file to a file having your ID as the name. Then remove the file of your name.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 37
Introduction to Linux (CSP3213)
Program 9

Aim: Compressing files: tar, gzip, compress, uncompress, file

1. Tar- is archiving utility in Linux. With tar command we can archive multiple files and
directories into a single file, extension of that file is “.tar”. gzip and bzip compression
techniques can be used with tar command.

Syntax : # tar [options] [name of tar file to be created] [list of files & directories to be
included]

Options:
-A, --catenate, --concatenate ----> append tar files to an archive
-c, --create ----> create a new archive
-d, --diff, --compare ---> find differences between archive and file system
--delete ---> delete from the archive (not on mag tapes!)
-r, --append ---> append files to the end of an archive
-t, --list ----> list the contents of an archive
--test-label ---> test the archive volume label and exit
-u, --update ---> only append files newer than copy in archive
-x, --extract, --get ----> extract files from an archive

Example:1 Create an Archive File


Syntax : # tar cvf <archive-Name>.tar /<file-OR-Directories To Be archived>
# tar cvf /mnt/backup.tar /etc /usr
Above command will archive all the files and directories of /etc and /usr in backup.tar file.

Example:2 Extract the data from the archive file.


# tar xpvf backup.tar -C /mnt/
Above Command will extract files or directories in /mnt folder.

2. gzip- Gzip reduces the size of the named files using Lempel-Ziv coding (LZ77). Whenever
possible, each file is replaced by one with the extension .gz, while keeping the same
ownership modes, access and modification times. (The default extension is -gz for
VMS, z for MSDOS, OS/2 FAT, Windows NT FAT and Atari.) If no files are specified, or if a
file name is "-", the standard input is compressed to the standard output. Gzip will only
attempt to compress regular files. In particular, it will ignore symbolic links.

Syntax : gzip [ -acdfhlLnNrtvV19 ] [-S suffix] [ name ... ]

Example:
gzip myfile
Compresses the file myfile, making it myfile.gz.
Note. When doing this the original file will no longer exist on the drive.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 38
Introduction to Linux (CSP3213)

3. compress : Reduces the size of the file. and adds the extension .Z

Syntax: compress <filename>.

4. uncompress /zcat : Restores a compressed file.

Syntax: uncompress <filename>


Syntax: zcat <filename>

Learning Outcome:

Commands related to archiving and compressing of files is learned.

VIVA QUESTIONS

 What is the zcat command used for?


 What do you mean by archiving?
 Give commands for uncompressing a file?
 What is the purpose for gzip command?
 What are .tar files?
 What are .Z files?
 What extensions are given to the compressed files?
 Why do you need to compress the files?

ACTIVITY FOR THE STUDENTS

Access the man pages for all archiving commands and practice the commands with all
options given.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 39
Introduction to Linux (CSP3213)
Program 10

Aim: Directory oriented commands: cd, pwd, mkdir, rmdir, ls and its options.

1. cd Change directory.
Usage: cd

Eg: cd my-directory cd go to home directory cd .. go up one directory

2. pwd: Print working directory on the terminal.

3. ls: List the content of a directory.


Usage: ls [options] or ls [options]

Options: -l list all files in long format. (permissions, users, filesize,date, and time are
displayed).
-a list all files including those beginning with a “.”
-F list files distinguishing directories/ executables* symbolic links@
-R recursively list subdirectories encountered.

4. mkdir Create a new directory.


Usage: mkdir directory path

5. rmdir: Remove a directory if its empty.


Usage: rmdir directory-path

Learning Outcome:

Creating and removing directories and related commands are learned.

Viva Questions

 Identify the current directory you are working in.


 Briefly explain the output screen of the ls -l command.
 How will you identify the hidden files?
 What are .name files?
 What does the d in the first column of the ls –l signifies?
 What does the b in the first column of the ls –l signifies?
 What does the c in the first column of the ls –l signifies?
 What does the - in the first column of the ls –l signifies?
 What is the condition that is must, before you use the rmdir command?

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 40
Introduction to Linux (CSP3213)
Activity for the students

Create a directory by your section name; the directory must contain files of all the
students by their name. Give the snapshot of the output screen which shows the
permissions these files and the section directory has.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 41
Introduction to Linux (CSP3213)
Program 11

Aim: Searching: Search file or directory in directory structure using find and locate
command with various options, wildcards *,?, []

The locate utility program performs a search through a previously constructed database of
files and directories on your system, matching all entries that contain a specified character
string. This can sometimes result in a very long list.

To get a shorter more relevant list we can use the grep program as a filter; grep will print
only the lines that contain one or more specified strings as in:

$ locate zip | grep bin

which will list all files and directories with both "zip" and "bin" in their name .

locate utilizes the database created by another program, updatedb. Most Linux systems run
this automatically once a day. However, you can update it at any time by just
running updatedb from the command line as the root user.

Wildcards and Matching File Names

You can search for a filename containing specific characters using wildcards.

Wildcard Result

? Matches any single character

* Matches any string of characters

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 42
Introduction to Linux (CSP3213)

[set] Matches any character in the set of characters, for example [adf] will
match any occurrence of "a", "d", or "f"

[!set] Matches any character not in the set of characters

To search for files using the ? wildcard, replace each unknown character with ?, e.g. if you
know only the first 2 letters are 'ba' of a 3-letter filename with an extension of .out, type ls
ba?.out .

To search for files using the * wildcard, replace the unknown string with *, e.g. if you
remember only that the extension was.out, type ls *.out

Finding files in the directory

find is extremely useful and often-used utility program in the daily life of a Linux system
administrator. It traverses down the filesystem tree from any particular directory (or set of
directories) and locates files that match specified conditions. The default pathname is
always the present working directory.

For example, administrators sometimes scan for large core files (which contain diagnostic
information after a program fails) that are more than several weeks old in order to remove
them. It is also common to remove files in /tmp (and other temporary directories, such as
those containing cached files) that have not been accessed recently. Many distros use
automated scripts that run periodically to accomplish such house cleaning.

When no arguments are given, find lists all files in the current directory and all of its
subdirectories. Commonly used options to shorten the list include -name (only list files with
a certain pattern in their name), -iname (also ignore the case of file names), and -
type (which will restrict the results to files of a certain specified type, such as d for
directory, l for symbolic link or f for a regular file, etc).

Searching for files and directories named "gcc":


$ find /usr -name gcc

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 43
Introduction to Linux (CSP3213)
Searching only for directories named "gcc":
$ find /usr -type d -name gcc

Searching only for regular files named "test1":


$ find /usr -type f -name test1

Finding based on time:


$ find / -ctime 3

Here, -ctime is when the inode meta-data (i.e., file ownership, permissions, etc) last
changed; it is often, but not necessarily when the file was first created. You can also search
for accessed/last read (-atime) or modified/last written (-mtime) times. The number is the
number of days and can be expressed as either a number (n) that means exactly that value,
+n which means greater than that number, or -n which means less than that number. There
are similar options for times in minutes (as in -cmin, -amin, and -mmin).

Finding based on sizes:

$ find / -size 0

Note the size here is in 512-byte blocks, by default; you can also specify bytes (c), kilobytes
(k), megabytes (M), gigabytes (G), etc. As with the time numbers above, file sizes can also be
exact numbers (n), +n or -n. For details consult the man page for find.

Learning Outcome:

To locate and find files using command line.

Viva Questions

 Give all the available options for find command


 What is the difference between locate and grep?
 What database the locate command searches for?
 List all the wildcards available.
 What are zip files?
 Give the command to find the file using its size.
 Give the command to find the file using its access time.
 Give the command to find the file using its modification time.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 44
Introduction to Linux (CSP3213)
 Give the command to find files by its name but ignoring the case.

ACTIVITY FOR THE STUDENTS

List all the files that have been accessed and modified in past two days.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 45
Introduction to Linux (CSP3213)
Program 12

Aim: Mounting: mount, umount. USB, CD/DVD

Mounting USB pen drive

1. In Ubuntu desktop, the USB pen drive will be detected and mounted automatically. In
ubuntu server command line terminal, a message will appear to notice you that some
information about the USB pen drive that has been plug in or alternatively you can
use fdisk command to check whether USB has been mounted or not.
Then you can get mount location by using mount command

2. If Step 1 didn't work for you, then run dmesg command to identify the correct device
name corresponding to the USB pen drive

$ dmesg

[19197.235469] sd 25:0:0:0: [sdb] Write Protect is off


[19197.235476] sd 25:0:0:0: [sdb] Mode Sense: 0b 00 00 08

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 46
Introduction to Linux (CSP3213)
[19197.236972] sd 25:0:0:0: [sdb] No Caching mode page present
[19197.236982] sd 25:0:0:0: [sdb] Assuming drive cache: write through
[19197.242047] sd 25:0:0:0: [sdb] No Caching mode page present
[19197.242055] sd 25:0:0:0: [sdb] Assuming drive cache: write through
[19197.279672] sdb: sdb1 --> Device name
[19197.282401] sd 25:0:0:0: [sdb] No Caching mode page present
[19197.282406] sd 25:0:0:0: [sdb] Assuming drive cache: write through
[19197.282410] sd 25:0:0:0: [sdb] Attached SCSI removable disk
[19199.953227] usb 2-1.1: USB disconnect, device number 28

2. a. Create Mount Point

$ mkdir -p /media/usb

2. b. Mount USB pen drive

$ sudo mount /dev/sdb1 /media/usb

Unmounting USB pen drive

1. To unmount a USB device simply run the following command

$ sudo umount /dev/sdb1

OR

$ sudo umount /media/usb

NOTE: /media/usb is a mount point.

Formatting USB pen drive

1. First make sure that USB device is not mounted, if it is then unmount it.

2. Format USB device in fat32 format

$ sudo mkfs.vfat /dev/sdb1

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 47
Introduction to Linux (CSP3213)

Note: You can use mkfs.ext3 to format to ext3 filesystem.

Caution: Enter your device name correctly otherwise it will wip out your entire data.

3. Format and change the Label of the USB drive.

$ sudo mkfs.vfat -n 'sandeep' /dev/sdb1

Mount/Unmount CD/DVD

In order to use a CD-ROM under Linux (or any Unix-like operating system), you must
first mount it. Mounting a CD-ROM (or any other physical media, such as a floppy disk, a ZIP
disk or a hard drive) tells the operating system which block device to use and where that
device is to appear within the directory tree — the mount point. Once you have finished
using the CD-ROM, you must unmount it.

Mounting the CD-ROM

The canonical command to mount the CD-ROM under Linux is:

# mount -t iso9660 -o ro device dir

The block device device specifies the physical device or bus the CD-ROM is attached to. On
most Linux systems, you can use /dev/cdrom, which would be a symbolic link to something
like /dev/hdc for an ATAPI CD-ROM, selected as a master device, on the secondary IDE
cable.

The mount point dir specifies where the contents of the CD-ROM are to appear. In Linux and
other Unix-like operating systems, every file and directory that can be accessed appears in a
single directory tree starting from “/”, the root directory. The mount point dir, then, is
simply a directory within that directory tree.

You can use any directory that you like for the mount point dir, as long as that directory
exists and is empty. The convention under Linux is to use either /mnt/cdrom or/cdrom.

So, for a typical Linux system, the command you would use to mount a CD-ROM would be:

# mount -t iso9660 -o ro /dev/cdrom /mnt/cdrom

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 48
Introduction to Linux (CSP3213)
Remember that only the root superuser can run this version of the mount command, so you
need to log in as root to do this. For the safety and security of your own computer, you
should log out as soon as you have entered this command successfully.

Accessing the CD-ROM

Once you have mounted the CD-ROM, you can access files and directories on that CD-ROM
as if they were part of your directory tree — as, in fact, they now are. For example, if you
mounted the CD-ROM on /mnt/cdrom, you can view the file you are now reading (stored on
the CD-ROM as unsw/common/cdrom-mounting.html) by typing something like:

$ more /mnt/cdrom/unsw/common/cdrom-mounting.html

Of course, if you used a different mount point than /mnt/cdrom, substitute that mount
point as appropriate. For example, if you used /cdrom, you would type:

$ more /cdrom/unsw/common/cdrom-mounting.html

To free you from the hassles of mounting and unmounting CD-ROMs in the Laboratory, you
can access the contents of this Companion CD-ROM by using ~course/cdrominstead
of /mnt/cdrom. For example, if you are studying ELEC2041, you can
use ~elec2041/cdrom on the Laboratory computers — and you don’t have to mount or
unmount any CD-ROMs:

$ more ~elec2041/cdrom/unsw/common/cdrom-mounting.html

Unmounting the CD-ROM

Once you have finished using the CD-ROM, you need to unmount it. The operating system
makes you do this so that it can check that nothing is, in fact, using the CD-ROM when you
try to eject it.

To unmount the CD-ROM, you need to enter the following command as the root superuser:

# umount dir

The directory dir is the mount point that you used for mounting the CD-ROM in the first
place (eg, /mnt/cdrom). And please note that the command is umount, notunmount: the
first “n” is missing!

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 49
Introduction to Linux (CSP3213)
If you get an error message stating that “device is busy”, it means that something is still
using files and/or directories on the CD-ROM. Even something as simple as having your
current directory set to some directory on the CD-ROM is enough to get you this message.

Learning Outcome:

 Mount, unmount and format USB drive

 Mount, Access and unmount CD/DVD drive.

Viva Questions

 What do you mean by mounting?


 What do you mean by unmounting?
 What does the /dev dir is for?
 What does the –p option in mkdir state?
 What do you mean by mount point?
 In which directory will you find the media devices?
 Give command to mount a CD-ROM.
 Give command to create a mount point
 Give command to mount A USB
 Give command to unmount a USB.

Activity for the students

Mount a USB and change its name to your name.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 50
Introduction to Linux (CSP3213)

Program 13

Aim: GCC: Working with GCC compiler, debugging, time-stamping, compiling object files
etc.

Compilation Steps

Compiling a Program
$ gcc -Wall main.c hello_fn.c -o newhello

Creating object files from source files using compile only option -c
$ gcc -Wall -c main.c

Creating executables from object files and linking them together


$ gcc main.o hello_fn.o -o hello

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 51
Introduction to Linux (CSP3213)
The resulting executable file can now be run:
$ ./hello

Link order of object files.


$ gcc main.o hello_fn.o -o hello (correct order)
$ gcc hello_fn.o main.o -o hello (incorrect order)

Linking with external libraries

#include <math.h>
#include <stdio.h>
void main (void){
double x = sqrt (2.0);
printf ("The square root of 2.0 is %f\n", x);
}
$ gcc -Wall calc.c /usr/lib/libm.a -o calc
$ gcc -Wall calc.c -lm -o calc
$ gcc -Wall -lm calc.c -o calc (incorrect order)
$ gcc -Wall calc.c -lm -o calc (correct order)
Compiling with optimization
$ gcc -Wall -O0 test.c -lm
Timestamp
$ time ./a.out
real 0m13.388s
user 0m13.370s
sys 0m0.010s

Learning Outcome:
 Debugging with gcc compiler
 Time-stamping with gcc
 Compiling object files with gcc

VIVA QUESTIONS
 What do you mean by timestamp?
 Write a command to compile the file file1
 Write a command to execute the file file1
 Create the source file from object files
 Why do you need a compiler?
 How will you change the name of the object file being created at the time of
compilation?
 What do you mean by assembling?
 What are linkers?

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 52
Introduction to Linux (CSP3213)
 What are loaders?

ACTIVITY FOR THE STUDENTS


Write a program to add two numbers and compile and execute using gcc compiler.

Program 14

Aim: Create the following file hierarchy using mkdir and touch command. (The bold letters
depicts directories)
Chitkara

Rajpura Baddi

Student.txt faculty.txt Mgt.txt

$ mkdir chitkara
$ cd chitkara
$ mkdir Rajpura
$ mkdir Baddi
$ cd Rajpura
$ touch Student.txt
$ cd Baddi
$ touch faculty.txt
$ touch mgt.txt

Learning Outcome:
Creating file and directory hierarchy structure.

Viva Questions
 What is the difference between cat and touch command.
 Explain the touch command
 What is the cd command used for?
 What is the mkdir command used for?
 What is the difference between directory and files?
 Give the command to change the permissions of directories.
 Give the command to change the permissions of files.
 How will you check who is the owner of directory rajpura.
 How will you check who is the owner of directory baddi.

ACTIVITY FOR THE STUDENTS


Create the above hierarchy using cat instead of touch command.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 53
Introduction to Linux (CSP3213)

Program 15
Aim: File system: Introduction to file system, File system Architecture, Comparing Files
and File Types.

In Linux (and all UNIX-like operating systems) it is often said “Everything is a file”, or at
least it is treated as such. This means whether you are dealing with normal data files and
documents, or with devices such as sound cards and printers, you interact with them
through the same kind of Input/output (I/O) operations. This simplifies things: you open a
“file” and perform normal operations like reading the file and writing on it.

On many systems (including Linux), the file system is structured like a tree. The tree is
usually portrayed as inverted, and starts at what is most often called the root
directory, which marks the beginning of the hierarchical filesystem and is also sometimes
referred to as the trunk, or simply denoted by /. The root directory is not the same as the

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 54
Introduction to Linux (CSP3213)
root user. The hierarchical filesystem also contains other elements in the path (directory
names) which are separated by forward slashes (/) as in /usr/bin/awk, where the last
element is the actual file name.

File system architecture

Overview of Home Directories


Now that you know about the basics of filesystems, let's learn about the filesystem
architecture and directory structure in Linux.

Each user has a home directory, usually placed under /home. The/root (slash-root) directory
on modern Linux systems is no more than the root user's home directory.

The /home directory is often mounted as a separate filesystem on its own partition, or even
exported (shared) remotely on a network through NFS.

Sometimes you may group users based on their department or function. You can then
create subdirectories under the /home directory for each of these groups. For example, a
school may organize /home with something like the following:

/home/faculty/
/home/staff/
/home/students/

In this section, you will learn to identify and differentiate between the different directories
available in Linux.

The /bin and /sbin Directories

The /bin directory contains executable binaries, essential commands used in single-user
mode, and essential commands required by all system users, such as given in the table
below.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 55
Introduction to Linux (CSP3213)

Usage

ps Produces a list of processes along with status information for the system.

ls Produces a listing of the contents of a directory.

cp Used to copy files.

To view a list of programs in the /bin directory, type: ls /bin

Commands that are not essential for the system in single-user mode are placed in
the /usr/bindirectory, while the /sbin directory is used for essential binaries related to
system administration, such as ifconfig and shutdown. There is also a /usr/sbin directory for
less essential system administration programs.

Sometimes /usr is a separate filesystem that may not be available/mounted in single-user


mode. This was why essential commands were separated from non-essential commands.
However, in some of the most modern Linux systems this distinction is considered obsolete,
and /usr/binand /bin are actually just linked together as are /usr/sbin and /sbin.

The /dev Directory

The /dev directory contains device nodes, a type of pseudo-file used by most hardware
and software devices, except for network devices. This directory is:

 Empty on the disk partition when it is not mounted

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 56
Introduction to Linux (CSP3213)
 Contains entries which are created by the udev system, which creates and manages
device nodes on Linux, creating them dynamically when devices are found.
The /dev directory contains items such as:

 /dev/sda1 (first partition on the first hard disk)

 /dev/lp1 (second printer)

 /dev/dvd1 (first DVD drive)


The /var and /etc Directories

The /var directory contains files that are expected to change in size and content as the
system is running (varstands for variable) such as the entries in the following
directories:

 System log files: /var/log

 Packages and database files: /var/lib

 Print queues: /var/spool

 Temp files: /var/tmp

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 57
Introduction to Linux (CSP3213)

The /var directory may be put in its own filesystem so that growth of the files can be
accommodated and the file sizes do not fatally affect the system. Network services
directories such as /var/ftp (the FTP service) and /var/www (the HTTP web service) are also
found under /var.

The /etc directory is the home for system configuration files. It contains no binary programs,
although there are some executable scripts. For example, the file resolv.conf tells the
system where to go on the network to obtain host name to IP address mappings (DNS). Files
likepasswd,shadow and group for managing user accounts are found in the /etc directory.
System run level scripts are found in subdirectories of /etc. For example, /etc/rc2.d contains
links to scripts for entering and leaving run level 2. The rc directory historically stood for Run
Commands. Some distros extend the contents of /etc. For example, Red Hat adds
thesysconfig subdirectory that contains more configuration files.

The /boot Directory

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 58
Introduction to Linux (CSP3213)
The /boot directory contains the few essential files needed to boot the system. For every
alternative kernel installed on the system there are four files:

1. vmlinuz: the compressed Linux kernel, required for booting

2. initramfs: the initial ram filesystem, required for booting, sometimes called initrd, not
initramfs

3. config: the kernel configuration file, only used for debugging and bookkeeping

4. System.map: kernel symbol table, only used for debugging

Each of these files has a kernel version appended to its name. The Grand Unified
Bootloader (GRUB) files are also found under the /boot directory.

The /lib and /media Directories

/lib contains libraries (common code shared by applications and needed for them to
run) for the essential programs in /bin and /sbin. These library filenames either start
with ld or lib, for example, /lib/libncurses.so.5.7.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 59
Introduction to Linux (CSP3213)
Most of these are what are known asdynamically loaded libraries (also known as shared
libraries or Shared Objects (SO)). On some Linux distributions there exists a /lib64 directory
containing 64-bit libraries, while /lib contains 32-bit versions.

Kernel modules (kernel code, often device drivers, that can be loaded and unloaded without
re-starting the system) are located in /lib/modules/<kernel-version-number>.

The /media directory is typically located where removable media, such as CDs, DVDs and
USB drives are mounted. Unless configuration prohibits it, Linux automatically mounts the
removable media in the /media directory when they are detected.

Comparing Files

Now that you know about the filesystem and its structure, let’s learn how to manage files
and directories.

diff is used to compare files and directories. This often-used utiility program has many
useful options (see man diff) including:

diff Option Usage

-c Provides a listing of differences that include 3 lines of context before


and after the lines differing in content

-r Used to recursively compare subdirectories as well as the current


directory

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 60
Introduction to Linux (CSP3213)

-i Ignore the case of letters

-w Ignore differences in spaces and tabs (white space)

To compare two files, at the command prompt, type diff <filename1><filename2>

In this section, you will learn additional methods for comparing files and how to
apply patches to files.

Using diff3 and patch

You can compare three files at once usingdiff3, which uses one file as the reference
basis for the other two. For example, suppose you and a co-worker both have made
modifications to the same file working at the same time independently. diff3 can show the
differences based on the common file you both started with. The syntax fordiff3 is as
follows:

$ diff3 MY-FILE COMMON-FILE YOUR-FILE

The graphic shows the use of diff3.

Many modifications to source code and configuration files are distributed utilizing patches,
which are applied, not suprisingly, with the patch program. A patch file contains
the deltas (changes) required to update an older version of a file to the new one. The patch
files are actually produced by running diff with the correct options, as in:

$ diff -Nur originalfile newfile > patchfile

Distributing just the patch is more concise and efficient than distributing the entire file. For
example, if only one line needs to change in a file that contains 1,000 lines, the patch file
will be just a few lines long.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 61
Introduction to Linux (CSP3213)
To apply a patch you can just do either of the two methods below:

$ patch -p1 < patchfile


$ patch originalfile patchfile

The first usage is more common as it is often used to apply changes to an entire directory
tree, rather than just one file as in the second example. To understand the use of the -
p1 option and many others, see the man page for patch.

Using the 'file' utility

In Linux, a file's extension often does not categorize it the way it might in other
operating systems. One cannot assume that a file named file.txt is a text file and not an
executable program. In Linux a file name is generally more meaningful to the user of the
system than the system itself; in fact most applications directly examine a file's contents to
see what kind of object it is rather than relying on an extension. This is very different from
the way Windows handles filenames, where a filename ending with .exe, for example,
represents an executable binary file.

The real nature of a file can be ascertained by using the file utility. For the file names given
as arguments, it examines the contents and certain characteristics to determine whether
the files are plain text, shared libraries, executable programs, scripts, or something else.

Learning Outcome:

 Explore the filesystem and its hierarchy.

 Explain the filesystem architecture

Viva Questions

 What is the function of diff command?


 What is the difference between diff and diff3?
 What is the difference between bin and sbin?
 Give the full form for GRUB.
 What is patch command used for?
 What is the difference between diff and diff3?

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 62
Introduction to Linux (CSP3213)
 List the option use with diff to ignore case.
 List the option use with diff to ignore spaces.

ACTIVITY FOR THE STUDENTS

Create a file by your section name having name of all the students of your section, create
another file by your subsection name having name of ll the students in your subsection.
Compare the two files using all the comparison commands.

Program 16

Aim: Text Editors: Basic Editors: nano and gedit, More Advanced Editors: vi and emacs.

Text editors: Basic editors


Nano is a text editor suited to working in UNIX. It is not as powerful as PC window-based
editors, as it does not rely on the mouse, but still has many useful features.

Most nano commands are invoked by holding down the Ctrl key (that is, the control key),
and pressing one of the other keys. In this text, the control key is referred to using ^. For
example, ^X means ``hold down the CTRL key and press the x key''. Most of the important
commands are listed at the bottom of your screen.

^G nano help

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 63
Introduction to Linux (CSP3213)
Starting nano

To edit a file called filename, type nano filename.

In nano, you can insert another file:

^R read an existing file into nano (inserted at the current cursor position)
^T opens a browser that allows you to select a file name from a list of files and directories

Navigation

The usual mouse-based point-and-click method is not supported by nano. Use


the arrow keys to move around the page in nano.

Other navigation commands:

^A move to beginning of line


^E move to end of line
^Y move down a page
^V move up a page
^_ move to a specific line (^_^V moves to the top of the file, ^_^Y to the bottom)
^C find out what line the cursor is currently on
^W search for some text.

When searching, you will be prompted for the text to search for. It searches from the
current cursor position, wrapping back up to the top if necessary.

Editing

Insert new text at the current cursor position just by typing the text in.

Delete commands:

^D delete character currently under the cursor


BackSpace delete character currently in front of the cursor
^K delete entire line
^\ search for (and replace) a string of characters

Cut and paste

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 64
Introduction to Linux (CSP3213)
^K does not delete lines permanently; the most recent set of deletions are stored in a
buffer. These lines may be re-inserted at the current cursor location using ^U. This may be
used to simulate cut and paste:

 Repeatedly use ^K until all of the text you want to move has been deleted.
 Move to the line that you want to insert the text at, and use ^U.

Note that pressing ^U more than once will cause multiple copies to be inserted. This is
particularly useful if you want to copy text:

 Repeatedly use ^K until all of the text you want to copy has been deleted.
 Press ^U immediately to put a copy back in its original location.
 Move to the line that you want to copy the text to, and use ^U.

Saving and Exiting

^O save contents without exiting (you will be prompted for a file to save to)
^X exit nano (you will be prompted to save your file if you haven't)
when saving a file, opens a browser that allows you to select a file name from a list of
^T files and directories.

Gedit :
gedit - simple text editor for GNOME

The gedit application is a simple text editor. You can use gedit to create and edit text files.
You can use gedit plugins to perform a variety of tasks related to text-editing from within
the gedit window. Light-weight text editor Gedit has all the basic features you come to
expect from a simple text editor, but Gedit has a native graphic user interface (GUI). Gedit
also has command line arguments available to users to quickly and easily view and edit files
from a terminal. Overall, Gedit is an easy to use text editor with utilizing the powerful
capabilities of the GNOME desktop. Gedit has a versatile plug-in architecture to extend its
capablilties. This allows you to perform functions you don't normally expect from a text
editor, such as piping the output of a shell command to the screen. The plug-in architecture
also lets you email people, browse the internet, or produce a diff from gedit.

SYNTAX
gedit [--help] [--debug[-section]] [--new-window] [--new-document] [--quit] [filename(s)...]

DESCRIPTION

gedit is a text editor for the GNOME Desktop.


OPTIONS

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 65
Introduction to Linux (CSP3213)
--help
Prints the command line options.

--debug[-section]
Runs gedit in debug mode. In debug mode function names are dumped to the
console when they are invoked. Specific sections for debugging are allowed. The
sections are: window, commands, document, file, plugins, prefs, print, search, undo,
view and recent. Run `gedit --help' for more information.

--new-window

Create a new toplevel window in an existing instance of gedit.

--new-document

Create a new document in an existing instance of gedit.

--quit
Quit an existing instance of gedit.

filename(s)...
Specifies the file to open when gedit starts - if this is not specified, gedit will load a
blank file with an Untitled label. Multiple files can be loaded if they are separated by
spaces. gedit also supports handling of remote files. For example, you can pass the
location of a webpage to gedit, like "http://www.gnome.org", or load a file from a
FTP server, like "ftp://ftp.gnome.org/robots.txt".

PIPES

Gedit accepts pipes, so it can be run after another command to load the output into gedit.
For example :

ls -l | gedit

Advance editors: vi editor

What is vi?

The default editor that comes with the UNIX operating system is called vi (visual editor).
[Alternate editors for UNIX environments include pico and emacs, a product of GNU.]

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 66
Introduction to Linux (CSP3213)
The UNIX vi editor is a full screen editor and has two modes of operation:

1. Command mode commands which cause action to be taken on the file, and
2. Insert mode in which entered text is inserted into the file.

In the command mode, every character typed is a command that does something to the text
file being edited; a character typed in the command mode may even cause the vi editor to
enter the insert mode. In the insert mode, every character typed is added to the text in the
file; pressing the <Esc> (Escape) key turns off the Insert mode.
While there are a number of vi commands, just a handful of these is usually sufficient for
beginning vi users. To assist such users, this Web page contains a sampling of
basic vi commands. The most basic and useful commands are marked with an asterisk (* or
star) in the tables below. With practice, these commands should become automatic.
NOTE: Both UNIX and vi are case-sensitive. Be sure not to use a capital letter in place of a
lowercase letter; the results will not be what you expect.

To Get Into and Out Of vi

To Start vi

To use vi on a file, type in vi filename. If the file named filename exists, then the first page
(or screen) of the file will be displayed; if the file does not exist, then an empty file and
screen are created into which you may enter text.
* vi filename edit filename starting at line 1
vi -r filename recover filename that was being edited when system crashed

To Exit vi

Usually the new or modified file is saved when you leave vi. However, it is also possible to
quit vi without saving the file.
Note: The cursor moves to bottom of screen whenever a colon (:) is typed. This type of
command is completed by hitting the <Return> (or <Enter>) key.
* :x<Return> quit vi, writing out modified file to file named in original invocation
:wq<Return> quit vi, writing out modified file to file named in original invocation
:q<Return> quit (or exit) vi
* :q!<Return> quit vi even though latest changes have not been saved for this vi call

Moving the Cursor

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 67
Introduction to Linux (CSP3213)
Unlike many of the PC and MacIntosh editors, the mouse does not move the cursor within
the vi editor screen (or window). You must use the the key commands listed below. On
some UNIX platforms, the arrow keys may be used as well; however, since vi was designed
with the Qwerty keyboard (containing no arrow keys) in mind, the arrow keys sometimes
produce strange effects in vi and should be avoided.
If you go back and forth between a PC environment and a UNIX environment, you may find
that this dissimilarity in methods for cursor movement is the most frustrating difference
between the two.
In the table below, the symbol ^ before a letter means that the <Ctrl> key should be held
down while the letter key is pressed.

*j or <Return> or down- Move cursor down one line


arrow
* k [or up-arrow] move cursor up one line
*h or <Backspace>
move cursor left one character
[or left-arrow]
*l or <Space>
move cursor right one character
[or right-arrow]
move cursor to start of current line (the
0 (zero)
one with the cursor)
$ move cursor to end of current line
w move cursor to beginning of next word
move cursor back to beginning of
b
preceding word
:0<Return> or 1G move cursor to first line in file
:n<Return> or nG move cursor to line n
:$<Return> or G move cursor to last line in file

Screen Manipulation
The following commands allow the vi editor screen (or window) to move up or down
several lines and to be refreshed.
^f move forward one screen
^b move backward one screen
^d move down (forward) one half screen
^u move up (back) one half screen
^l redraws the screen
^r redraws the screen, removing deleted lines

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 68
Introduction to Linux (CSP3213)
Adding, Changing, and Deleting Text

Unlike PC editors, you cannot replace or delete text by highlighting it with the
mouse. Instead use the commands in the following tables.
Perhaps the most important command is the one that allows you to back up
and undo your last action. Unfortunately, this command acts like a toggle, undoing
and redoing your most recent action. You cannot go back more than one step.
* u UNDO WHATEVER YOU JUST DID; a simple toggle
The main purpose of an editor is to create, add, or modify text for a file.

Inserting or Adding Text

The following commands allow you to insert and add text. Each of these commands
puts the vi editor into insert mode; thus, the <Esc> key must be pressed to terminate
the entry of text and to put the vi editor back into command mode.
* i insert text before cursor, until <Esc> hit
I insert text at beginning of current line, until <Esc> hit
* a append text after cursor, until <Esc> hit
A append text to end of current line, until <Esc> hit
* o open and put text in a new line below current line, until <Esc> hit
* O open and put text in a new line above current line, until <Esc> hit

Changing Text

The following commands allow you to modify text.


*r replace single character under cursor (no <Esc> needed)
R replace characters, starting with current cursor position, until <Esc> hit
change the current word with new text,
cw
starting with the character under cursor, until <Esc> hit
change N words beginning with character under cursor, until <Esc> hit;
cNw
e.g., c5w changes 5 words
C change (replace) the characters in the current line, until <Esc> hit
cc change (replace) the entire current line, stopping when <Esc> is hit
change (replace) the next N lines, starting with the current line,
Ncc or cNc
stopping when <Esc> is hit

Deleting Text

The following commands allow you to delete text.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 69
Introduction to Linux (CSP3213)
*x delete single character under cursor
Nx delete N characters, starting with character under cursor
dw delete the single word beginning with character under cursor
delete N words beginning with character under cursor;
dNw
e.g., d5w deletes 5 words
D delete the remainder of the line, starting with current cursor position
* dd delete entire current line
delete N lines, beginning with the current line;
Ndd or dNd
e.g., 5dd deletes 5 lines

Cutting and Pasting Text

The following commands allow you to copy and paste text.


yy copy (yank, cut) the current line into the buffer
Nyy or yNy copy (yank, cut) the next N lines, including the current line, into the buffer
p put (paste) the line(s) in the buffer into the text after the current line
Other Commands: Searching Text
A common occurrence in text editing is to replace one word or phase by another. To
locate instances of particular sets of characters (or strings), use the following
commands.
/string search forward for occurrence of string in text
?string search backward for occurrence of string in text
n move to next occurrence of search string
N move to next occurrence of search string in opposite direction

Determining Line Numbers

Being able to determine the line number of the current line or the total number of
lines in the file being edited is sometimes useful.
:.= returns line number of current line at bottom of screen
:= returns the total number of lines at bottom of screen
provides the current line number, along with the total number of lines,
^g
in the file at the bottom of the screen

Saving and Reading Files

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 70
Introduction to Linux (CSP3213)
These commands permit you to input and output files other than the named file with which
you are currently working.

read file named filename and insert after current line


:r filename<Return>
(the line with cursor)
:w<Return> write current contents to file named in original vi call
:w newfile<Return> write current contents to a new file named newfile
write the contents of the lines numbered 12 through 35 to a
:12,35w smallfile<Return>
new file named smallfile
:w! prevfile<Return> write current contents over a pre-existing file named prevfile

Emacs editor
Emacs is another editor available in UNIX. Like vi, emacs is a screen editor.
Unlike vi, emacs is not an insertion mode editor, meaning that any character typed
in emacs is automatically inserted into the file, unless it includes a command prefix.
Commands in emacs are either control characters (hold down the <Ctrl> key while
typing another character) or are prefixed by one of a set of reserved
characters: <Esc> or <Ctrl>-X. The <Esc> key can be typed by itself (because it really
is a character) and then followed by another character; the <Ctrl>key must be held
down while the next character is being typed. The conventions for describing these
characters (since it takes too long to type out the whole thing)
are ESC means <Esc> and C- means <Ctrl>.
One other distinction between emacs and vi is that emacs allows you to edit several
files at once. The window for emacs can be divided into several windows, each of
which contains a view into a buffer. Each buffer typically corresponds to a different
file. Many of the commands listed below are for reading files into new buffers and
moving between buffers.
To use emacs on a file, type
emacs filename
If the file named filename exists, then the first screen's worth of the file is displayed;
if it doesn't exist, a help message is displayed.
The easiest way to learn emacs is to start it up and go through the on-line tutorial. To
access the on-line tutorial, type ESC help-with-tutorial immediately after you have
started emacs. The tutorial directs you further in learning the basic commands. One
notational point you should know is that the tutorial uses M- to mean ESC.
To give you a head start, the following table lists the basic commands you need to
know to use emacs to edit a file. An asterisk (* or star) to the left of a command
indicate it is one to learn immediately.

Help Commands

* C-h help-command: first character in lots of useful help commands

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 71
Introduction to Linux (CSP3213)
* C-h t help-with-tutorial: command to run the tutorial
C-h i information: describes most of the emacs commands in man style pages
C-h k describe-key: tells you what a particular key stroke does
command-apropos: prompts for a string and
* C-h a
then searches for all emacs commands that contains that string
ESC ? also does command-apropos
* C-h ? help-for-help: describes how to use the help facilities

File Reading and Writing Commands

find-file: first prompts for a filename and


* C-x C-f
then loads that file into a editor buffer of the same name
* C-x C-s save-buffer: saves the buffer into the associated filename
C-x C-w write-named-file: prompts for a new filename and writes the buffer into it

Cursor/Screen Movement Commands

Depending on the terminal, some of the cursor movement can be handled by the
arrow keys.
* C-a move cursor to (at) beginning-of-line
C-e move cursor to end-of-line
* C-f move cursor forward one character
* C-b move cursor backward one character
* C-n move cursor to next line
* C-p move cursor to previous line
C-v scroll file forward by one screenful
ESC v scroll file backward by one screenful
* ESC < go to beginning-of-buffer
* ESC > go to end-of-buffer
ESC f move cursor forward one word
ESC b move cursor backward one word

Copy and Delete Commands

C-d delete-char: delete character under cursor


ESC d delete-word: delete from cursor to end of word immediately ahead of the cursor

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 72
Introduction to Linux (CSP3213)
* C-k kill-line: delete the rest of the current line
set-mark-command: mark is used to indicate the beginning of an area of text to be
* C-@
yanked
* C-w kill-region: delete the area of text between the mark and the current cursor position
* C-y yank: insert at current cursor location whatever was most recently deleted
ESC copy-region-as-kill: copy area between mark and cursor into kill-buffer
w so that it can be yanked into someplace else

Search Commands

isearch-forward: prompts for text string and


* C-s
then searches from the current cursor position forwards in the buffer
isearch-backward: like isearch-forward,
C-r
but searches from the current cursor position to end of buffer for text string
query-replace: prompts for a search string and
ESC %
a string with which to replace the search string

Window and Buffer Commands

C-x 0 zero-window: deletes current window


double-window: splits current window into two parts,
C-x 2 allowing you to edit at two different locations in the same file
or permitting you to view two different files at the same time
C-x b switch-to-buffer: display a different buffer on the screen
other-window: move the cursor to the other window
C-x o
(assuming that you have two windows/buffers open at once
* C-x C-b list-buffers: lists those buffers currently loaded into emacs

Exiting Emacs, Fixing Mistakes and Other Important Stuff

save-buffers-kill-emacs: when you are finished editing,


* C-x C-c to save the edited but unsaved buffers
and to return you to the UNIX prompt
keyboard-quit: if while typing a command you make a mistake and want to stop,
* C-g
this aborts a command in progress
universal-argument: if you want to do a command several times,
type this command
C-u
followed by a number (for the number of times)
followed by the command you wish repeated

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 73
Introduction to Linux (CSP3213)
* C-x u undo: undoes the last command typed, in case you made a mistake
execute-extended-command: prompts for the name of an emacs command;
allows you to execute a command
* ESC x
if you know roughly what it is called
but cannot remember the key strokes for it

Learning Outcome:
Knowledge of Basic and Advanced editors

Viva Questions
 What is gedit?
 How will you start and exit the vi editor?
 What is the significance of pipe | operator?
 Why do we need an editor?
 Name a terminal based editor.
 Is nano a terminal based editor or not?
 Enlist a difference between gedit and vi editor.
 Give the command to quit and save a file using vi editor.

ACTIVITY FOR THE STUDENTS

Enlist atleast 5 differences between all the editors mentioned in the above program.

Program 17

Aim: Communication-oriented commands: echo, host, nslookup, ipcalc, ping, traceroute,


netstat

1. echo - display a line of text

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 74
Introduction to Linux (CSP3213)
SYNOPSIS

echo [OPTION]... [STRING]...

DESCRIPTION

NOTE: your shell may have its own version of echo which will supercede the version
described here. Please refer to your shell's documentation for details about the options it
supports.

Echo the STRING(s) to standard output.

-n: do not output the trailing newline


-e: enable interpretation of the backslash-escaped characters listed below
-E: disable interpretation of those sequences in STRINGs
--help: display this help and exit
--version: output version information and exit

2.host - DNS lookup utility

SYNOPSIS

host [ -aCdlnrTwv ] [ -c class ] [ -N ndots ] [ -R number ] [ -t type ] [ -W wait ] name [ server]

DESCRIPTION

host is a simple utility for performing DNS lookups. It is normally used to convert names to
IP addresses and vice versa. When no arguments or options are given, host prints a short
summary of its command line arguments and options.

name is the domain name that is to be looked up. It can also be a dotted-decimal IPv4
address or a colon-delimited IPv6 address, in which case host will by default perform a
reverse lookup for that address. server is an optional argument which is either the name or
IP address of the name server that host should query instead of the server or servers listed
in /etc/resolv.conf.

The -a (all) option is equivalent to setting the -v option and asking host to make a query of
type ANY.

When the -C option is used, host will attempt to display the SOA records for
zone name from all the listed authoritative name servers for that zone. The list of name
servers is defined by the NS records that are found for the zone.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 75
Introduction to Linux (CSP3213)
The -c option instructs to make a DNS query of class class. This can be used to lookup Hesiod
or Chaosnet class resource records. The default class is IN (Internet).

Verbose output is generated by host when the -d or -v option is used. The two options are
equivalent. They have been provided for backwards compatibility. In previous versions, the -
doption switched on debugging traces and -v enabled verbose output.

List mode is selected by the -l option. This makes host perform a zone transfer for
zone name. The argument is provided for compatibility with older implemementations. This
option is equivalent to making a query of type AXFR.

The -n option specifies that reverse lookups of IPv6 addresses should use the IP6.INT
domain and "nibble" labels as defined in RFC1886. The default is to use IP6.ARPA and binary
labels as defined in RFC2874.

The -N option sets the number of dots that have to be in name for it to be considered
absolute. The default value is that defined using the ndots statement in /etc/resolv.conf, or
1 if no ndots statement is present. Names with fewer dots are interpreted as relative names
and will be searched for in the domains listed in the search or domain directive
in /etc/resolv.conf.

The number of UDP retries for a lookup can be changed with the -
R option. number indicates how many times host will repeat a query that does not get
answered. The default number of retries is 1. If number is negative or zero, the number of
retries will default to 1.

Non-recursive queries can be made via the -r option. Setting this option clears the RD ---
recursion desired --- bit in the query which host makes. This should mean that the name
server receiving the query will not attempt to resolve name. The -r option enables host to
mimic the behaviour of a name server by making non-recursive queries and expecting to
receive answers to those queries that are usually referrals to other name servers.

By default host uses UDP when making queries. The -T option makes it use a TCP connection
when querying the name server. TCP will be automatically selected for queries that require
it, such as zone transfer (AXFR) requests.

The -t option is used to select the query type. type can be any recognised query type:
CNAME, NS, SOA, SIG, KEY, AXFR, etc. When no query type is specified, host automatically
selects an appropriate query type. By default it looks for A records, but if the -C option was
given, queries will be made for SOA records, and if name is a dotted-decimal IPv4 address or
colon-delimited IPv6 address, host will query for PTR records.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 76
Introduction to Linux (CSP3213)
The time to wait for a reply can be controlled through the -W and -w options. The -W option
makes host wait for wait seconds. If wait is less than one, the wait interval is set to one
second. When the -w option is used, host will effectively wait forever for a reply. The time
to wait for a response will be set to the number of seconds given by the hardware's
maximum value for an integer quantity.

3. nslookup - query Internet name servers interactively

SYNOPSIS

nslookup [-option ... ] [host-to-find | -[server ] ]

DESCRIPTION

Nslookup is a program to query Internet domain name servers. Nslookup has two modes:
interactive and non-interactive. Interactive mode allows the user to query name servers for
information about various hosts and domains or to print a list of hosts in a domain. Non-
interactive mode is used to print just the name and requested information for a host or
domain.

ARGUMENTS

Interactive mode is entered in the following cases:

a)when no arguments are given (the default name server will be used),
b)when the first argument is a hyphen (-) and the second argument is the host name or
Internet address of a name server.

Non-interactive mode is used when the name or Internet address of the host to be looked
up is given as the first argument. The optional second argument specifies the host name or
address of a name server.

The options listed under the ``set '' command below can be specified in the .nslookuprc file
in the user's home directory if they are listed one per line. Options can also be specified on
the command line if they precede the arguments and are prefixed with a hyphen. For
example, to change the default query type to host information, and the initial timeout to 10
seconds, type:

nslookup -query=hinfo -timeout=10

4.ipcalc - perform simple manipulation of IP addresses

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 77
Introduction to Linux (CSP3213)
SYNOPSIS

ipcalc [OPTION]... <IP address>[/prefix] [netmask]

DESCRIPTION

ipcalc provides a simple way to calculate IP information for a host. The various options
specify what information ipcalc should display on standard out. Multiple options may be
specified. An IP address to operate on must always be specified. Most operations also
require a netmask or a CIDR prefix as well.
OPTIONS
-b, --broadcast
Display the broadcast address for the given IP address and netmask.

-h, --hostname
Display the hostname for the given IP address.

-m, --netmask
Calculate the netmask for the given IP address. It assumes that the IP address is in a
complete class A, B, or C network. Many networks do not use the default netmasks,
in which case an inappropriate value will be returned.

-p, --prefix
Show the prefix for the given mask/IP address.

-n, --network
Display the network address for the given IP address and netmask.

-s, --silent
Don't ever display error messages.

5. ping, ping6 - send ICMP ECHO_REQUEST to network hosts

SYNOPSIS

ping [ -LRUbdfnqrvVaAB] [ -c count] [ -i interval] [ -l preload] [ -p pattern] [ -s packetsize] [ -


tttl] [ -w deadline] [ -F flowlabel] [ -I interface] [ -M hint] [ -Q tos] [ -S sndbuf] [ -T timestamp
option] [ -W timeout] [ hop ...] destination

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 78
Introduction to Linux (CSP3213)
DESCRIPTION

ping uses the ICMP protocol's mandatory ECHO_REQUEST datagram to elicit an ICMP
ECHO_RESPONSE from a host or gateway. ECHO_REQUEST datagrams (``pings'') have an IP
and ICMP header, followed by a struct timeval and then an arbitrary number of ``pad'' bytes
used to fill out the packet.

OPTIONS

-a
Audible ping.

-A
Adaptive ping. Interpacket interval adapts to round-trip time, so that effectively not
more than one (or more, if preload is set) unanswered probes present in the
network. Minimal interval is 200msec for not super-user. On networks with low rtt
this mode is essentially equivalent to flood mode.

6. traceroute - print the route packets take to network host

SYNOPSIS

traceroute [ -dFInrvx ] [ -f first_ttl ] [ -g gateway ]

[ -i iface ] [ -m max_ttl ] [ -p port ]

[ -q nqueries ] [ -s src_addr ] [ -t tos ]

[ -w waittime ] [ -z pausemsecs ]

host [ packetlen ]

DESCRIPTION

The Internet is a large and complex aggregation of network hardware, connected together
by gateways. Tracking the route one's packets follow (or finding the miscreant gateway
that's discarding your packets) can be difficult. Traceroute utilizes the IP protocol `time to
live' field and attempts to elicit an ICMP TIME_EXCEEDED response from each gateway
along the path to some host.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 79
Introduction to Linux (CSP3213)
The only mandatory parameter is the destination host name or IP number. The default
probe datagram length is 40 bytes, but this may be increased by specifying a packet length
(in bytes) after the destination host name.

Other options are:

-f
Set the initial time-to-live used in the first outgoing probe packet.

-F
Set the "don't fragment" bit

-d
Enable socket level debugging.

-g
Specify a loose source route gateway (8 maximum).

7. netstat - Print network connections, routing tables, interface statistics, masquerade


connections, and multicast memberships
By default, netstat displays a list of open sockets. If you don't specify any address families,
then the active sockets of all configured address families will be printed.

--route , -r

Display the kernel routing tables.

--groups , -g

Display multicast group membership information for IPv4 and IPv6.

--interface=iface , -i

Display a table of all network interfaces, or the specified iface).

--masquerade , -M

Display a list of masqueraded connections.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 80
Introduction to Linux (CSP3213)
--statistics , -s

Display summary statistics for each protocol.

Learning Outcome:

Communication Oriented Commands are learned

Viva Questions

 Trace route makes use of which protocol?


 What filed of IP protocol is used by the tracroute command to trace the route?
 What command is used to calculate IP information from host?
 What are the two different modes nslookup works in? Explain them briefly.
 What is the ipcalc command used for?
 What is the nslookup command used for?
 What is the ip command used for?
 Give the command to display the summary statistics for each protocol?

ACTIVITY FOR THE STUDENTS

Print the list of open sockets and all the masquerade connections for the network you are
connected to.

Program 18

Aim: Communication-oriented commands: whois, finger, ifconfig, telnet, wget, ip, route,
iptables, write, mesg, mail

1. whois is a client for the WHOIS directory service.

Syntax:

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 81
Introduction to Linux (CSP3213)
whois [ -h HOST ] [ -p PORT ] [ -aCFHlLMmrRSVx ] [ -g SOURCE:FIRST-LAST ]
[ -i ATTR ] [ -S SOURCE ] [ -T TYPE ] object

whois -t TYPE

whois -v TYPE

whois -q keyword

Description:

whois searches for an object in a WHOIS database. WHOIS is a queryand response protocol
that is widely used for querying databases that store the registered users of an
Internetresource, such as a domain name or an IPaddress block, but is also used for a wider
range of other information.

Most modern versions of whois try to guess the right server to ask for the specified object. If
no guess can be made, whois will connect to whois.networksolutions.com for NIC handles
or whois.arin.net for IPv4addresses and network names.

Options:

-hHOST Connect to WHOIS database host HOST.


-H Suppress the display of legal disclaimers.
-pPORT When connecting, connect to network port PORT.
--verbose Operate verbosely
--help Display a help message, and exit.

2. finger

finger - user information lookup program

SYNOPSIS:

finger [-lmsp ] [user ... ] [user@host ... ]

DESCRIPTION:

The finger displays information about the system users.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 82
Introduction to Linux (CSP3213)
Options are:

-s
Finger displays the user's login name, real name, terminal name and write status (as a
``*'' after the terminal name if write permission is denied), idle time, login time, office
location and office phone number.

Login time is displayed as month, day, hours and minutes, unless more than six months
ago, in which case the year is displayed rather than the hours and minutes.

Unknown devices as well as nonexistent idle and login times are displayed as single
asterisks.

-l
Produces a multi-line format displaying all of the information described for the -s
option as well as the user's home directory, home phone number, login shell, mail
status, and the contents of the files ``.plan '' ``.project '' ``.pgpkey '' and ``.forward ''
from the user's home directory.

Phone numbers specified as eleven digits are printed as ``+N-NNN-NNN-NNNN''.


Numbers specified as ten or seven digits are printed as the appropriate subset of that
string. Numbers specified as five digits are printed as ``xN-NNNN''. Numbers specified
as four digits are printed as ``xNNNN''.

If write permission is denied to the device, the phrase ``(messages off)'' is appended to
the line containing the device name. One entry per user is displayed with the -l option;
if a user is logged on multiple times, terminal information is repeated once per login.

Mail status is shown as ``No Mail.'' if there is no mail at all, ``Mail last read DDD MMM
## HH:MM YYYY (TZ)'' if the person has looked at their mailbox since new mail arriving,
or ``New mail received ...'', `` Unread since ...'' if they have new mail.

-p
Prevents the -l option of finger from displaying the contents of the ``.plan '' ``.project ''
and ``.pgpkey '' files.
-m
Prevent matching of user names. User is usually a login name; however, matching will
also be done on the users' real names, unless the -m option is supplied. All name
matching performed by finger is case insensitive.

If no options are specified, finger defaults to the -l style output if operands are provided,
otherwise to the -s style. Note that some fields may be missing, in either format, if

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 83
Introduction to Linux (CSP3213)
information is not available for them.

If no arguments are specified, finger will print an entry for each user currently logged into
the system.

Finger may be used to look up users on a remote machine. The format is to specify a user as
``user@host'' or ``@host '' where the default output format for the former is the -l style,
and the default output format for the latter is the -s style. The -l option is the only option
that may be passed to a remote machine.

3. ifconfig

ifconfig is used to configure or view the configuration of, a networkinterface.

ifconfig stands for "interface configuration". It is used to view and change the configuration
of the network interfaces on your system.

Running the ifconfig command with no arguments, like this:

ifconfig

...will display information about all network interfaces currently in operation. The output will
resemble the following:

eth0 Link encap:Ethernet HWaddr 09:00:12:90:e3:e5


inet addr:192.168.1.29 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::a00:27ff:fe70:e3f5/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:54071 errors:1 dropped:0 overruns:0 frame:0
TX packets:48515 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:22009423 (20.9 MiB) TX bytes:25690847 (24.5 MiB)
Interrupt:10 Base address:0xd020

lo Link encap:Local Loopback


inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:83 errors:0 dropped:0 overruns:0 frame:0
TX packets:83 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:7766 (7.5 KiB) TX bytes:7766 (7.5 KiB)

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 84
Introduction to Linux (CSP3213)
wlan0 Link encap:Ethernet HWaddr 58:a2:c2:93:27:36
inet addr:192.168.1.64 Bcast:192.168.2.255 Mask:255.255.255.0
inet6 addr: fe80::6aa3:c4ff:fe93:4746/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:436968 errors:0 dropped:0 overruns:0 frame:0
TX packets:364103 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:115886055 (110.5 MiB) TX bytes:83286188 (79.4 MiB)

Here, eth0, lo and wlan0 are the names of the active network interfaces on the system.

 eth0 is the first Ethernet interface. (Additional ethernet interfaces would be named
eth1, eth2, etc.) This type of interface is usually a NICconnected to the network by a
category 5cable.

 lo is the loopback interface. This is a special network interface that the system uses
to communicate with itself.
 wlan0 is the name of the first wireless network interface on the system. Additional
wireless interfaces would be named wlan1, wlan2, etc.

These are the traditional naming conventions for network interfaces under Linux; other
operating systems may have different names. For instance, under many BSDoperating
systems, ethernet interfaces are named em0, em1, etc. Check your configuration, or consult
your documentation, to determine the exact names of your own interfaces.

Viewing the Configuration Of All Interfaces

If you'd like to view the configuration of all network interfaces on the system (not just the
ones that are currently active), you can specify the -a option, like this:

ifconfig -a

This will produce output similar to simply running ifconfig, but if there are any inactive
interfaces on the system, their configuration will also be displayed.

4. telnet

The telnet program is a user interfaceto the TELNET protocol

Syntax:

telnet [-468ELadr] [-S tos] [-b address] [-e escapechar] [-l user] [-n tracefile] [host [port]]

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 85
Introduction to Linux (CSP3213)
Description:

The telnet command is used for interactivecommunication with another host using the
TELNET protocol. It begins in command mode, where it prints a telnet command prompt
("telnet>").

If telnet is invoked with a host argument, it performs an open command implicitly.

Options:
-4 Force IPv4 address resolution.

-6 Force IPv6 address resolution.

Host Specifies a host to contact over the network

Specifies a port number or service name to contact. If not specified, the telnet port
Port
(23) is used.

Examples

telnet myhost.com

Attempts to open a connection to the remote host myhost.com. If a connection is


established, the host will prompt for a login name and password.

telnet -l myusername myhost.com:5555

Attempts to open a connection to the remote host myhost.com on port 5555, using the
login name myusername. If successful, the host will prompt for myusername's password.

telnet

Opens a local telnet> prompt, where you can enter any of the commands listed above. For
example, entering the following command at the prompt:

telnet> open myhost.com

5. wget

wget stands for "web get". It is a command-lineutilitywhich downloads files over a network.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 86
Introduction to Linux (CSP3213)
Syntax:
wget [option]... [URL]...

Description:
wget is a free utility for non-interactive download of files from the web. It supports HTTP,
HTTPS, and FTP protocols, as well as retrieval through HTTP proxies.

wget is non-interactive, meaning that it can work in the background, while the user is not
logged on. This allows you to start a retrieval and disconnect from the system, letting
wgetfinish the work. By contrast, most web browsersrequire constant user interaction,
which make transferring a lot of data difficult.

wget can follow links in HTMLand XHTML pages and create local versions of remote
websites, fully recreating the directorystructure of the original site. This is sometimes called
"recursive downloading.'' While doing that, wget respects the Robot Exclusion Standard
(robots.txt). wget can be instructed to convert the links in downloaded HTML files to the
local files for offline viewing.

wget has been designed for robustness over slow or unstable network connections; if a
download fails due to a network problem, it will keep retrying until the whole file has been
retrieved. If the server supports regetting, it will instruct the server to continue the
download from where it left off.

Overview

The simplest way to use wget is to simply provide it with the location of a file to download
over HTTP. For example, to download the file http://website.com/files/file.zip, this
command:

wget http://website.com/files/file.zip

...would download the file into the working directory.

Examples
wget http://www.computerhope.com/

Download the default homepage file (index.htm) from www.computerhope.com. The file
will be saved to the working directory.

 wget --limit-rate=200k http://www.example.org/files/archive.zip

Download the file archive.zip from www.example.org, and limit bandwidth usage of the

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 87
Introduction to Linux (CSP3213)
download to 200k/s.

 wget -c http://www.example.org/files/archive.zip

Download archive.zip from example.org, and if a partial download exists in the current
directory, resume the download where it left off.

 wget -b http://www.example.org/files/archive.zip

Download archive.zip in the background, returning you to the command prompt in the
interim.

 wget --spider http://www.example.org/files/archive.zip

Uses "web spider" mode to check if a remote file exists. Output will resemble the following:

Spider mode enabled. Check if remote file exists.


HTTP request sent, awaiting response... 200 OK
Length: 1206 (1.2K) [application/zip]
Remote file exists.

 wget --mirror -p --convert-links -P ./example-mirror http://www.example.org

Download a complete mirror of the website www.example.org to the folder. /example-


mirror for local viewing.

 wget -Q5m http://www.example.org/files/archive.zip

Stop downloading archive.zip once 5megabytes have been successfully transferred. This
transfer can then later be resumed using the -c option.

6. ip

Show and manipulate routing, devices, policy routing and tunnels.

Syntax:

ip [ OPTIONS ] OBJECT { COMMAND | help }

where OBJECT may be:

{ link | addr | addrlabel | route | rule | neigh | ntable | tunnel |


tuntap maddr | mroute | mrule | monitor | xfrm | netns | l2tp | tcp_metrics }

and OPTIONS may be:

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 88
Introduction to Linux (CSP3213)
{ -V[ersion] | -s[tatistics] | -r[esolve] | -f[amily]
{ inet | inet6 | ipx | dnet | link } | -o[neline] }

OPTIONS:

-V, -Version print the version of the ip utility and exit.

-s, -stats, - Output more information. If the option appears twice or more, the amount of
statistics information increases. As a rule, the information is statistics or some time values.

Specify maximum number of loops the 'ip addr flush' logic will attempt before giving
-l, -loops
up. The default is 10. Zero ("0") means loop until all addresses are removed.

followed by protocol family identifier: inet, inet6, bridge, ipx, dnet or link, enforce
the protocol family to use. If the option is not present, the protocol family is guessed
-f, -family from other arguments. If the rest of the command line does not give enough
information to guess the family, ip falls back to the default one, usually inet or any.
link is a special family identifier meaning that no networking protocol is involved.

-4 shortcut for -family inet.

-6 shortcut for -family inet6.

-B shortcut for -family bridge.

-0 shortcut for -family link.

output each record on a single line, replacing line feeds with the '\' character. This is
-o, -oneline
convenient when you want to count records with wc or to grep the output.

-r, -resolve use the system's name resolver to print DNS names instead of host addresses.

7. route

Show or manipulate the IProuting table.


In computer networking, a router is a device responsible for forwarding network traffic.
When datagrams arrive at a router, the router must determine the best way to route them to
their destination.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 89
Introduction to Linux (CSP3213)
On Linux, BSD, and other Unix-like systems, the route command is used to view and make
changes to the kernel routing table. The command syntax is different on different systems;
here, when it comes to specific command syntax, we'll be discussing the Linux version.

Running route at the command line without any options will display the routing table
entries:

route

Kernel IP routing table


Destination Gateway Genmask Flags Metric Ref Use Iface
default 192.168.1.2 0.0.0.0 UG 1024 0 0 eth0
192.168.1.0 * 255.255.255.0 U 0 0 0 eth0

This shows us how the system is currently configured. If a packet comes into the system and
has a destination in the range 192.168.2.0 through 192.168.2.255, then it is forwarded to
the gateway *, which is 0.0.0.0 — a special address which represents an invalid or non-
existant destination. So, in this case, our system will not route these packets.

If the destination is not in this IP address range, it is forwarded to the default gateway (in
this case, 192.168.1.2, and that system will determine how to forward the traffic on to the
next step towards its destination.

8. iptables : administration tool for IPv4 packet filtering and NAT

SYNOPSIS:

iptables [-ttable] {-A|-C|-D} chainrule-specification

iptables [-ttable] -Ichain [rulenum] rule-specification

iptables [-ttable] -Rchain rulenum rule-specification

iptables [-ttable] -Dchain rulenum

iptables [-ttable] -S [chain [rulenum]]

iptables [-ttable] {-F|-L|-Z} [chain [rulenum]] [options...]

iptables [-ttable] -Nchain

iptables [-ttable] -X [chain]

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 90
Introduction to Linux (CSP3213)
iptables [-ttable] -Pchain target

iptables [-ttable] -Eold-chain-name new-chain-name

rule-specification = [matches...] [target]

match = -mmatchname [per-match-options]

target = -jtargetname [per-target-options]

DESCRIPTION:

Iptables is used to set up, maintain, and inspect the tables of IPv4 packet filter rules in the
Linux kernel. Several different tables may be defined. Each table contains a number of built-
in chains and may also contain user-defined chains.

Each chain is a list of rules which can match a set of packets. Each rule specifies what to do
with a packet that matches. This is called a `target', which may be a jump to a user-defined
chain in the same table.

OPTIONS:

The options that are recognized by iptables can be divided into several different groups.

COMMANDS
These options specify the desired action to perform. Only one of them can be specified on
the command line unless otherwise stated below. For long versions of the command and
option names, you need to use only enough letters to ensure that iptables can differentiate
it from all other options.

-A, --appendchain rule-specification


Append one or more rules to the end of the selected chain. When the source and/or
destination names resolve to more than one address, a rule will be added for each
possible address combination.
-C, --checkchain rule-specification
Check whether a rule matching the specification does exist in the selected chain. This
command uses the same logic as -D to find a matching entry, but does not alter the
existing iptables configuration and uses its exit code to indicate success or failure.
-D, --deletechain rule-specification
-D, --deletechain rulenum
Delete one or more rules from the selected chain. There are two versions of this
command: the rule can be specified as a number in the chain (starting at 1 for the first
rule) or a rule to match.
-I, --insertchain [rulenum] rule-specification
Insert one or more rules in the selected chain as the given rule number. So, if the rule

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 91
Introduction to Linux (CSP3213)
number is 1, the rule or rules are inserted at the head of the chain. This is also the
default if no rule number is specified.
-R, --replacechain rulenum rule-specification
Replace a rule in the selected chain. If the source and/or destination names resolve to
multiple addresses, the command will fail. Rules are numbered starting at 1.
-L, --list [chain]
List all rules in the selected chain. If no chain is selected, all chains are listed. Like every
other iptables command, it applies to the specified table (filter is the default), so NAT
rules get listed by

iptables -t nat -n -L

Please note that it is often used with the -n option, in order to avoid long reverse DNS
lookups. It is legal to specify the -Z (zero) option as well, in which case the chain(s) will
be atomically listed and zeroed. The exact output is affected by the other arguments
given. The exact rules are suppressed until you use

iptables -L -v

-S, --list-rules [chain]


Print all rules in the selected chain. If no chain is selected, all chains are printed like
iptables-save. Like every other iptables command, it applies to the specified table
(filter is the default).
-F, --flush [chain]
Flush the selected chain (all the chains in the table if none is given). This is equivalent
to deleting all the rules one by one.
-Z, --zero [chain [rulenum]]
Zero the packet and byte counters in all chains, or only the given chain, or only the
given rule in a chain. It is legal to specify the -L, --list (list) option as well, to see the
counters immediately before they are cleared. (See above.)
-N, --new-chainchain
Create a new user-defined chain by the given name. There must be no target of that
name already.
-X,--delete-chain [chain]
Delete the optional user-defined chain specified. There must be no references to the
chain. If there are, you must delete or replace the referring rules before the chain can
be deleted. The chain must be empty, i.e. not contain any rules. If no argument is
given, it will attempt to delete every non-builtin chain in the table.
-P, --policychain target
Set the policy for the chain to the given target. See the section TARGETS for the legal
targets. Only built-in (non-user-defined) chains can have policies, and neither built-in
nor user-defined chains can be policy targets.
-E, --rename-chainold-chain new-chain
Rename the user specified chain to the user supplied name. This is cosmetic, and has

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 92
Introduction to Linux (CSP3213)
no effect on the structure of the table.
-h
Help. Give a (currently very brief) description of the command syntax.

PARAMETERS

The following parameters make up a rule specification (as used in the add, delete, insert,
replace and append commands).

-4, --ipv4
This option has no effect in iptables and iptables-restore.
-6, --ipv6
If a rule using the -6 option is inserted with (and only with) iptables-restore, it will be
silently ignored. Any other uses will throw an error. This option allows to put both IPv4
and IPv6 rules in a single rule file for use with both iptables-restore and ip6tables-
restore.
-p, --protocolprotocol
The protocol of the rule or of the packet to check. The specified protocol can be one of
tcp, udp, udplite, icmp, esp, ah, sctp or the special keyword "all", or it can be a
numeric value, representing one of these protocols or a different one. A protocol
name from /etc/protocols is also allowed. A "!" argument before the protocol inverts
the test. The number zero is equivalent to all. "all" will match with all protocols and is
taken as default when this option is omitted.
-s, --sourceaddress[/mask][,...]
Source specification. Address can be either a network name, a hostname, a network IP
address (with /mask), or a plain IP address. Hostnames will be resolved once only,
before the rule is submitted to the kernel. Please note that specifying any name to be
resolved with a remote query such as DNS is a really bad idea. The mask can be either
a network mask or a plain number, specifying the number of 1's at the left side of the
network mask. Thus, a mask of 24 is equivalent to 255.255.255.0. A "!" argument
before the address specification inverts the sense of the address. The flag --src is an
alias for this option. Multiple addresses can be specified, but this will expand to
multiple rules (when adding with -A), or will cause multiple rules to be deleted (with -
D).
-d, --destinationaddress[/mask][,...]
Destination specification. See the description of the -s (source) flag for a detailed
description of the syntax. The flag --dst is an alias for this option.
-m, --matchmatch
Specifies a match to use, that is, an extension module that tests for a specific property.
The set of matches make up the condition under which a target is invoked. Matches
are evaluated first to last as specified on the command line and work in short-circuit
fashion, i.e. if one extension yields false, evaluation will stop.
-j, --jumptarget
This specifies the target of the rule; i.e., what to do if the packet matches it. The target

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 93
Introduction to Linux (CSP3213)
can be a user-defined chain (other than the one this rule is in), one of the special
builtin targets which decide the fate of the packet immediately, or an extension (see
EXTENSIONS below). If this option is omitted in a rule (and -g is not used), then
matching the rule will have no effect on the packet's fate, but the counters on the rule
will be incremented.
-g, --gotochain
This specifies that the processing should continue in a user specified chain. Unlike the -
-jump option return will not continue processing in this chain but instead in the chain
that called us via --jump.
-i, --in-interfacename
Name of an interface via which a packet was received (only for packets entering the
INPUT, FORWARD and PREROUTING chains). When the "!" argument is used before
the interface name, the sense is inverted. If the interface name ends in a "+", then any
interface which begins with this name will match. If this option is omitted, any
interface name will match.
-o, --out-interfacename
Name of an interface via which a packet is going to be sent (for packets entering the
FORWARD, OUTPUT and POSTROUTING chains). When the "!" argument is used
before the interface name, the sense is inverted. If the interface name ends in a "+",
then any interface which begins with this name will match. If this option is omitted,
any interface name will match.
-f, --fragment
This means that the rule only refers to second and further fragments of fragmented
packets. Since there is no way to tell the source or destination ports of such a packet
(or ICMP type), such a packet will not match any rules which specify them. When the
"!" argument precedes the "-f" flag, the rule will only match head fragments, or
unfragmented packets.
-c, --set-counterspackets bytes
This enables the administrator to initialize the packet and byte counters of a rule
(during INSERT, APPEND, REPLACE operations).

OTHER OPTIONS

The following additional options can be specified:

-v, --verbose
Verbose output. This option makes the list command show the interface name, the
rule options (if any), and the TOS masks. The packet and byte counters are also listed,
with the suffix 'K', 'M' or 'G' for 1000, 1,000,000 and 1,000,000,000 multipliers
respectively (but see the -x flag to change this). For appending, insertion, deletion and
replacement, this causes detailed information on the rule or rules to be printed. -v
may be specified multiple times to possibly emit more detailed debug statements.
-w, --wait
Wait for the xtables lock. To prevent multiple instances of the program from running
concurrently, an attempt will be made to obtain an exclusive lock at launch. By default,

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 94
Introduction to Linux (CSP3213)
the program will exit if the lock cannot be obtained. This option will make the program
wait until the exclusive lock can be obtained.
-n, --numeric
Numeric output. IP addresses and port numbers will be printed in numeric format. By
default, the program will try to display them as host names, network names, or
services (whenever applicable).
-x, --exact
Expand numbers. Display the exact value of the packet and byte counters, instead of
only the rounded number in K's (multiples of 1000) M's (multiples of 1000K) or G's
(multiples of 1000M). This option is only relevant for the -L command.
--line-numbers
When listing rules, add line numbers to the beginning of each rule, corresponding to
that rule's position in the chain.
--modprobe=command
When adding or inserting rules into a chain, use command to load any necessary
modules (targets, match extensions, etc).

9. write

write sends a message to another user.

Syntax

write user [tty]

Description

The writeutility allows you to communicate with other users, by copying lines from your
terminal to theirs.

When you run the write command, the user you are writing to gets a message of the format:

Message from yourname@yourhost on yourtty at hh:mm ...

Any further lines you enter will be copied to the specified user's terminal. If the other user
wants to reply, they must run write as well.

When you are done, type an end-of-file or interruptcharacter. The other user will see the
message ‘EOF’ indicating that the conversation is over.

You can prevent people (other than the super-user) from writing to you with the mesg
command.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 95
Introduction to Linux (CSP3213)

If the user you want to write to is logged in on more than one terminal, you can specify
which terminal to write to by specifying the terminal name as the second operand to the
write command. Alternatively, you can let write select one of the terminals; it will pick the
one with the shortest idle time. This is so that if the user is logged in at work and also dialed
up from home, the message will go to the right place.

The traditional protocol for writing to someone is that the string ‘-o’, either at the end of a
line or on a line by itself, means that it is the other person's turn to talk. The string ‘oo’
means that the person believes the conversation to be over.

Options
user The user to write to.
The specific terminal to write to, if the user is logged in to more than one
tty
session.

Examples
write hope

Write a message to the user hope. After entering this command, you will be placed on a
blank line, where everything you type will be sent to the other user (line by line). Typing the
interrupt character (CTRL-C, by default) will return you to the command prompt, and end
the write session.

write hope tty7

Write a message to the user hope on terminal tty7.

10.mesg

The mesg command allows you control write access to your terminal by other users.

Syntax:
mesg [n|y]

Description:
The write command allows other users to send a message to your terminal session; the
mesg command is used to toggle these messages on or off.

Options
Prevents the display of terminal messages from other users. This is like using a "do not disturb"
n
sign.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 96
Introduction to Linux (CSP3213)
y Allows messages to be displayed on your screen.
If no option is given, mesg displays the current access state of your terminal.

Examples:
mesg y

Allow other users to send you messages.

mesg n

Disallow other users from being able to send you messages.

mesg

Display the current write status of your terminal.

11. mail

Send and receive mail.

Syntax
mail [OPTION...] [address...]

Options
-a, --append=HEADER: VALUE Append given header to the message being sent.
-e, --exist Return true if mail exists.
-E, --exec=COMMAND Execute COMMAND.
-f, --file[=URL] Operate on given mailbox URL. The default mailbox is ~/mbox.
-F, --byname Save messages according to sender.
-H, --headers Write a header summary and exit.
-i, --ignore Ignore interrupts.
-n, --norc Do not read the system mailrc file.
-N, --nosum Do not display initial header summary.
-p, --print Print all mail to standard output.
-q, --quit Cause interrupts to terminate program.
-r, --read Same as -p
-s, --subject=SUBJ Send a message with a Subject of SUBJ.
-t, --to Precede message by a list of addresses.
-u, --user=USER Operate on USER’s mailbox.
--license Print license and exit.
--external-locker=PATH Set full path of the external locker program
--lock-expire-timeout=SECONDS Number of seconds after which the lock expires.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 97
Introduction to Linux (CSP3213)
--lock-flags=FLAGS Default locker flags (E=external, R=retry, T=time, P=pid)
Set the maximum number of times to retry acquiring the
--lock-retry-count=NUMBER
lockfile.
--lock-retry-timeout=SECONDS Set timeout for acquiring the lockfile.
-m, --mail-spool=URL Use specified URL as a mail spool directory.
--mailbox-type=PROTO Default mailbox type to use.
--tls[=BOOL] Enable TLS support.
-?, --help Display a help message and exit.
--usage Display a short usage message and exit.
-V, --version Display program version and exit.

Examples
mesg y

Allow other users to send you messages.

mesg n

Disallow other users from being able to send you messages.

mesg

Display the current write status of your terminal.

11. mail

Opens the mail program and displays the first message in the mailbox, if any. If mail is found,
the user is placed at a mail command prompt; type ? for a list of commands.

mail support@computerhope.com

Starts a new e-mail addressed to support@computerhope.com. When finished composing


the message, type CTRL-D on a new line.

Learning Outcome: Commands to configure the network connections.

Viva Questions

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 98
Introduction to Linux (CSP3213)
 What is the difference is between write and mail command?
 What is the purpose of mesg command?
 What is the –s option for finger command used for?
 What command is used to configure the network interface?
 What is the purpose of route command?
 Give the command used for sending mails.
 Give the command to display messages on someone else’s terminal.
 What is the purpose of write command?
 How can you toggle on to receive messages send to you?
 How can you toggle off to receive messages send to you?

ACTIVITY FOR THE STUDENTS

Check if there is any inactive interfaces on the system. If yes display their configuration
information along with the active ones.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 99
Introduction to Linux (CSP3213)
Program 19
Aim: Managing Users: Adding and Removing Users using sudo Command.

Adding/Deleting Users
Adding a user is easy. The command used is: useradd “name of the user”

Note – You must be logged-in as root to add, delete, and modify users. It is not
recommended to stay logged-in as root other than when necessary and only certain
members should have root access.

Example:
useradd roman

You can then use “su” plus the name of the user you just added to logon. “exit” will take you
out.

The command for deleting a user is “userdel”.


userdel roman

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 100
Introduction to Linux (CSP3213)

These commands are very basic, but there are other options we have as well. Options:

 -d sets home directory for the user (if other than the default which is: /home/”user’s
name”)
 -m creates the home directory

Using the –d option on its own will only set the home directory for the user, but does not
create it.

You can see I confirm this by “echo $HOME” which tells me my home directory and I use “ls”
to confirm.

Adding the –m option will create the directory.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 101
Introduction to Linux (CSP3213)

If you just add the user, default directory is /home/”users name” and you can just use the –
m to create.

Lastly, using the “-r” option along with userdel will delete the user as well as the home
directory.

Changing Passwords
If you are logged in as root, the command is “username” password.

Example: passwd roman

If you are logged on as the user, the command is “passwd”.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 102
Introduction to Linux (CSP3213)

Adding Users to Groups


Let’s say we want to add roman to the group accounting. “-g” is used to change the user’s
primary group.

Command is: useradd –gaccounting roman

I then ran the grep command to confirm.

However, say I want to add roman to the group accounting and make his primary
group sales. We can add the “-G” option (other groups).

“-G” basically says add this user to a new group, but keep them in the old one (append).

Then issue command “id roman” – to confirm.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 103
Introduction to Linux (CSP3213)
We can use “-G” on its own to add a user to another group.

Note: The groups must exit before we can add users to them.

Modifying Users
If a user is created and you just want to add that user to a group, or change the home
directory, etc:

Example: usermod -Gmanagement roman

Or you can change the home directory for the user:

Example: usermod –d/home/newfolder roman

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 104
Introduction to Linux (CSP3213)
Creating Groups
The command for adding groups is “groupadd” or “groupdel”.

You can confirm by checking the /group/etc file.

Example: grep software /etc/group or cat /etc/group

The “groupdel” command will remove the group entirely.

Learning Outcome:
To add and delete the users by accessing the root user.

Viva Questions

 Give the command to remove the group entirely.


 Give the commands to change the home directory of the user.
 What is the default directory assigned to the user just added?
 Give the commands to add and delete a user.
 What is the purpose of id command?
 How can you check the UID of the new user added?
 How can you check the GID of the new user added?
 Give the command to change the primary group of the new user being added?
 Give the command to add a group to the primary group of the new user being added?

ACTIVITY FOR THE STUDENTS

Create a new user called user1 and this user to the sudo configuration file. Switch to this
new user and make sure you can execute root level commands.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 105
Introduction to Linux (CSP3213)
Program 20

Aim: Local Security Principles: Understanding Linux Security, Understand the Uses of root,
Using the sudo Command, Working with Passwords, permissions modification using
chmod. Chown, chgrp

User Accounts

The Linux kernel allows properly authenticated users to access files and applications. While
each user is identified by a unique integer (the user id or UID), a separate database
associates a username with each UID. Upon account creation, new user information
is added to the user database and the user's home directory must be created and populated
with some essential files. Command line programs such as useradd and userdel as well
as GUI tools are used for creating and removing accounts.

For each user, the following seven fields are maintained in the /etc/passwd file:

Field Name Details Remarks

Username User login name Should be between 1 and 32


characters long

Password User password (or the character x if the Is never shown in Linux when it is
password is stored in being typed; this stops prying
the /etc/shadow file) in encrypted eyes
format

 UID 0 is reserved for root


User ID Every user must have a user id (UID) user
(UID)
 UID's ranging from 1-99 are
reserved for other

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 106
Introduction to Linux (CSP3213)

predefined accounts

 UID's ranging from 100-999


are reserved for system
accounts and groups (except
for RHEL, which reserves
only up to 499)

 Normal users have UID's of


1000 or greater, except on
RHEL where they start at 500

Group ID The primary Group ID (GID); Group Will be covered in detail in the
(GID) Identification Number stored in chapter on Processes
the /etc/group file

User Info This field is optional and allows insertion For example: Rufus T. Firefly
of extra information about the user such
as their name

Home The absolute path location of user's For example: /home/rtfirefly


Directory home directory

Shell The absolute location of a For example: /bin/bash


user's default shell

Types of Accounts:

By default, Linux distinguishes between several account types in order to isolate processes
and workloads. Linux has four types of accounts:

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 107
Introduction to Linux (CSP3213)
 root

 System

 Normal

 Network

For a safe working environment, it is advised to grant the minimum privileges possible and
necessary to accounts, and remove inactive accounts. The last utility, which shows the last
time each user logged into the system, can be used to help identify potentially inactive
accounts which are candidates for system removal.

Understanding the root Account

Root is the most privileged account on a Linux/UNIX system. This account has the ability to
carry out all facets of system administration, including adding accounts, changing user
passwords, examining log files, installing software, etc. Utmost care must be taken when
using this account. It has no security restrictions imposed upon it.

When you are signed in as, or acting as root, the shell prompt displays '#’ (if you are
using bash and you haven’t customized the prompt as we discuss elsewhere in this course).
This convention is intended to serve as a warning to you of the absolute power of this
account.

Operations that
Require root
Privileges

root privileges are


required to perform
operations such as:

 Creating,
removing and
managing user
accounts.

 Managing
software

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 108
Introduction to Linux (CSP3213)
packages.

 Removing or modifying system files.

 Restarting system services.

Regular account users of Linux distributions may be allowed to install software packages,
update some settings, and apply various kinds of changes to the system.
However, root privilege is required for performing administration tasks such as restarting
services, manually installing packages and managing parts of the filesystem that are outside
the normal user’s directories.

Creating a New User Account

To create a new user account:

1. At the command prompt, as root type useradd <username>and press the ENTER key.

2. To set the initial password, type passwd <username> and press the ENTER key.
The New password: prompt is displayed.

3. Enter the password and press the ENTER key.


To confirm the password, the prompt Retype new password: is displayed.

4. Enter the password again and press the ENTER key.


The message passwd: all authentication tokens updated successfully. is displayed.

Comparing sudo and su

In Linux you can use either su or sudo to temporarily grant root access to a normal user;
these methods are actually quite different. Listed below are the differences between the
two commands.

su sudo

When elevating privilege, you need to enter When elevating privilege, you need to enter
the rootpassword. Giving the root the user’s password and not
password to a normal user

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 109
Introduction to Linux (CSP3213)

should never, ever be done. the root password.

Once a user elevates to the root account Offers more features and is considered
using su, the user can do anything that more secure and more configurable. Exactly
the root user can do for as long as the user what the user is allowed to do can be
wants, without being asked again for a precisely controlled and limited. By default
password. the user will either always have to keep
giving their password to do further
operations with sudo, or can avoid doing so
for a configurable time interval.

The command has limited logging features. The command has detailed logging
features.

Permissions

The Unix operating system (and likewise, Linux) differs from other computing environments
in that it is not only a multitasking system but it is also a multi-user system as well.

What exactly does this mean? It means that more than one user can be operating the
computer at the same time. While your computer will only have one keyboard and monitor,
it can still be used by more than one user. For example, if your computer is attached to a
network, or the Internet, remote users can log in via telnet or ssh (secure shell) and operate
the computer. In fact, remote users can execute X applications and have the graphical
output displayed on a remote computer. The X Windows system supports this.

The multi-user capability of Unix is not a recent "innovation," but rather a feature that is
deeply ingrained into the design of the operating system. If you remember the environment
in which Unix was created, this makes perfect sense. Years ago before computers were
"personal," they were large, expensive, and centralized. A typical university computer
system consisted of a large mainframe computer located in some building on campus
and terminals were located throughout the campus, each connected to the large central
computer. The computer would support many users at the same time.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 110
Introduction to Linux (CSP3213)
In order to make this practical, a method had to be devised to protect the users from each
other. After all, you could not allow the actions of one user to crash the computer, nor could
you allow one user to interfere with the files belonging to another user.

This lesson will cover the following commands:

 chmod - modify file access rights


 su - temporarily become the superuser
 chown - change file ownership
 chgrp - change a file's group ownership

File permissions

Linux uses the same permissions scheme as Unix. Each file and directory on your system is
assigned access rights for the owner of the file, the members of a group of related users,
and everybody else. Rights can be assigned to read a file, to write a file, and to execute a file
(i.e., run the file as a program).

To see the permission settings for a file, we can use the ls command as follows:

[me@linuxbox me]$ ls -l some_file

-rw-rw-r-- 1 me me 1097374 Sep 26 18:48 some_file

We can determine a lot from examining the results of this command:

 The file "some_file" is owned by user "me"


 User "me" has the right to read and write this file
 The file is owned by the group "me"
 Members of the group "me" can also read and write this file
 Everybody else can read this file

Let's try another example. We will look at the bash program which is located in
the /bin directory:

[me@linuxbox me]$ ls -l /bin/bash

-rwxr-xr-x 1 root root 316848 Feb 27 2000 /bin/bash

Here we can see:

 The file "/bin/bash" is owned by user "root"


 The superuser has the right to read, write, and execute this file

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 111
Introduction to Linux (CSP3213)
 The file is owned by the group "root"
 Members of the group "root" can also read and execute this file
 Everybody else can read and execute this file

In the diagram below, we see how the first portion of the listing is interpreted. It consists of
a character indicating the file type, followed by three sets of three characters that convey
the reading, writing and execution permission for the owner, group, and everybody else.

chmod

The chmod command is used to change the permissions of a file or directory. To use it, you
specify the desired permission settings and the file or files that you wish to modify. There
are two ways to specify the permissions, but I am only going to teach one way.

It is easy to think of the permission settings as a series of bits (which is how the computer
thinks about them). Here's how it works:

rwx rwx rwx = 111 111 111


rw- rw- rw- = 110 110 110
rwx --- --- = 111 000 000

and so on...

rwx = 111 in binary = 7


rw- = 110 in binary = 6
r-x = 101 in binary = 5
r-- = 100 in binary = 4

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 112
Introduction to Linux (CSP3213)
Now, if you represent each of the three sets of permissions (owner, group, and other) as a
single digit, you have a pretty convenient way of expressing the possible permissions
settings. For example, if we wanted to set some_file to have read and write permission for
the owner, but wanted to keep the file private from others, we would:

[me@linuxbox me]$ chmod 600 some_file

Here is a table of numbers that covers all the common settings. The ones beginning with "7"
are used with programs (since they enable execution) and the rest are for other kinds of
files.

Value Meaning

(rwxrwxrwx) No restrictions on permissions. Anybody may do anything. Generally


777
not a desirable setting.

(rwxr-xr-x) The file's owner may read, write, and execute the file. All others may
755 read and execute the file. This setting is common for programs that are used by all
users.

(rwx------) The file's owner may read, write, and execute the file. Nobody else has
700 any rights. This setting is useful for programs that only the owner may use and must
be kept private from others.

666 (rw-rw-rw-) All users may read and write the file.

(rw-r--r--) The owner may read and write a file, while all others may only read the
644 file. A common setting for data files that everybody may read, but only the owner
may change.

(rw-------) The owner may read and write a file. All others have no rights. A common
600
setting for data files that the owner wants to keep private.
Directory permissions

The chmod command can also be used to control the access permissions for directories. In
most ways, the permissions scheme for directories works the same way as they do with
files. However, the execution permission is used in a different way. It provides control for
access to file listing and other things. Here are some useful settings for directories:

Value Meaning

(rwxrwxrwx) No restrictions on permissions. Anybody may list files, create new files
777
in the directory and delete files in the directory. Generally not a good setting.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 113
Introduction to Linux (CSP3213)
(rwxr-xr-x) The directory owner has full access. All others may list the directory, but
755 cannot create files nor delete them. This setting is common for directories that you
wish to share with other users.

(rwx------) The directory owner has full access. Nobody else has any rights. This
700 setting is useful for directories that only the owner may use and must be kept
private from others.
Becoming the superuser for a short while

It is often useful to become the superuser to perform important system administration


tasks, but as you have been warned (and not just by me!), you should not stay logged on as
the superuser. In most distributions, there is a program that can give you temporary access
to the superuser's privileges. This program is called su (short for substitute user) and can be
used in those cases when you need to be the superuser for a small number of tasks. To
become the superuser, simply type the sucommand. You will be prompted for the
superuser's password:

[me@linuxbox me]$ su
Password:
[root@linuxbox me]#

After executing the su command, you have a new shell session as the superuser. To exit the
superuser session, type exitand you will return to your previous session.

In some distributions, most notably Ubuntu, an alternate method is used. Rather than
using su, these systems employ thesudo command instead. With sudo, one or more users
are granted superuser privileges on an as needed basis. To execute a command as the
superuser, the desired command is simply preceeded with the sudo command. After the
command is entered, the user is prompted for the user's password rather than the
superuser's:

[me@linuxbox me]$ sudo some_command


Password:
[me@linuxbox me]$

Changing file ownership

You can change the owner of a file by using the chown command. Here's an example:
Suppose I wanted to change the owner of some_file from "me" to "you". I could:

[me@linuxbox me]$ su
Password:
[root@linuxbox me]# chown you some_file

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 114
Introduction to Linux (CSP3213)
[root@linuxbox me]# exit
[me@linuxbox me]$

Notice that in order to change the owner of a file, you must be the superuser. To do this,
our example employed the sucommand, then we executed chown, and finally we
typed exit to return to our previous session.

chown works the same way on directories as it does on files.

Changing group ownership

The group ownership of a file or directory may be changed with chgrp. This command is
used like this:

[me@linuxbox me]$ chgrp new_group some_file

In the example above, we changed the group ownership of some_file from its previous
group to "new_group". You must be the owner of the file or directory to perform a chgrp.

Learning Outcome:

 Have a good grasp of best practices and tools for making Linux systems as secure as
possible.

 Understand the powers and dangers of using the root (superuser) account.

 Know how to use the sudo command to perform privileged operations while restricting
enhanced powers as much as feasible.

 Be able to explain the importance of process isolation and hardware access.

 Know how to work with passwords, including how to set and change them.

 Describe how to secure the boot process and hardware resources.

Viva Questions

 Compare su and sudo command.


 How can you change the ownership of a file or directory?
 Give the binary and relative values for no restriction on permissions.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 115
Introduction to Linux (CSP3213)
 Give the binary and relative values for owner to read and write a file.
 What does permissions 777 state?
 How can you assign rwxrwxrw using relative permissions?
 How can you assign rwxrwxrw using absolute permissions?
 Give the command to change the group of the file belongs to.
 Give the command to change the group as well as the owner to which the file
belongs to.
 What does umask states?

ACTIVITY FOR THE STUDENTS

 With a newly created user look at the password aging for the user, modify the
expiration date and check what has changed?

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 116
Introduction to Linux (CSP3213)

Program 21

Aim: Networking Operations: Introduction to Networking, Browsers, Graphical and non-


graphical Browsers, Transferring Files.

Network Operations:
a) Introduction to Networking: An Ubuntu machine can be connected to internet in two
ways - wired and wireless. Both ways require a network interface card, IP address, subnet
mask, default gateway, and DNS server. The foremost step is to find and configure a
network interface by using following command:

$ifconfig
eth0 Link encap:Ethernet HWaddr 00:21:9b:ef:a3:db
UP BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
Interrupt:16

lo Link encap:Local Loopback


inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:2826 errors:0 dropped:0 overruns:0 frame:0
TX packets:2826 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:572718 (572.7 KB) TX bytes:572718 (572.7 KB)

There are two interfaces in list – eth0 and lo. eth0 can be configured to access internet since
lo is the loopback interface. Following steps are followed to manually configure eth0.
1. Open System Settings->Network Connections.
2. Click on options button.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 117
Introduction to Linux (CSP3213)

3. Type a name of connection and click on Ipv4 settings tab.


4. Select Manual as the method of configuration.

5. Click on Add button and assign IP address, Netmask, and Gateway to the newly
created connection.
6. Add DNS servers and save the connection.

Interface can be configured automatically/dynamically if user selects automatically (DHCP)


as method of configuration. In that case, user is not required to enter IP address, Netmask,
Gateway, and DNS servers. Everything is assigned by DHCP server.

Once the configuration is over, ifconfig command can be used to verify it as shown below:
$ifconfig

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 118
Introduction to Linux (CSP3213)
eth0 Link encap:Ethernet HWaddr 4a:32:e4:a7:f5:0f

inet addr:10.0.0.11 Bcast:10.0.7.255 Mask:255.255.252.0

UP BROADCAST MULTICAST MTU:1500 Metric:1

RX packets:0 errors:0 dropped:0 overruns:0 frame:0

TX packets:0 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:0

RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)

Using ping and traceroute utility:


Ping utility is used to check connectivity between machines connected in a network.

$ping
ping www.google.com

PING www.google.com (216.58.220.36) 56(84) bytes of data.

64 bytes from maa03s18-in-f4.1e100.net (216.58.220.36): icmp_seq=1 ttl=55 time=256 ms

64 bytes from maa03s18-in-f4.1e100.net (216.58.220.36): icmp_seq=2 ttl=55 time=255 ms

^C

--- www.google.com ping statistics ---

8 packets transmitted, 8 received, 0% packet loss, time 7009ms

rtt min/avg/max/mdev = 246.509/253.514/266.642/5.998 ms

The ping command just shown continuously pings the host www.google.com. After a few
pings, press Ctrl+C to end the pings, and the last few lines show you how many of the ping
requests succeeded.

$traceroute

traceroute www.facebook.com

traceroute to www.facebook.com (31.13.79.246), 30 hops max, 60 byte packets

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 119
Introduction to Linux (CSP3213)

1 192.168.43.1 (192.168.43.1) 3.722 ms 3.614 ms 3.820 ms

2 10.124.160.65 (10.124.160.65) 174.911 ms 213.722 ms 252.738 ms

3 10.74.255.213 (10.74.255.213) 291.719 ms 291.767 ms 330.620 ms

4 * 10.124.132.131 (10.124.132.131) 408.558 ms *

5 115.113.247.5.static-delhi.vsnl.net.in (115.113.247.5) 463.357 ms 494.387 ms 533.414


ms

6 172.29.250.33 (172.29.250.33) 588.120 ms 389.569 ms 434.706 ms

7 ***

8 115.114.85.233 (115.114.85.233) 1758.523 ms 1760.283 ms 1776.138 ms

9 if-7-2.tcore1.CXR-Chennai.as6453.net (180.87.36.34) 1832.371 ms 1836.493 ms


1836.547 ms

10 if-5-2.tcore1.SVW-Singapore.as6453.net (180.87.12.53) 1838.321 ms 1846.200 ms


1846.844 ms

11 if-11-2.thar1.SVQ-Singapore.as6453.net (180.87.98.37) 1838.184 ms 1863.025 ms


1862.822 ms

12 180.87.98.42 (180.87.98.42) 1870.505 ms 179.403 ms 178.241 ms

13 psw01c.sin1.tfbnw.net (173.252.65.188) 173.014 ms psw01b.sin1.tfbnw.net


(173.252.65.189) 187.100 ms psw01d.sin1.tfbnw.net (173.252.65.187) 182.913 ms

14 msw1ao.01.sin1.tfbnw.net (173.252.66.31) 190.063 ms msw1ab.01.sin1.tfbnw.net


(173.252.66.33) 188.380 ms msw1ao.01.sin1.tfbnw.net (173.252.66.31) 189.951 ms

15 edge-star-shv-01-sin1.facebook.com (31.13.79.246) 192.872 ms 200.269 ms 183.852


ms

Using traceroute, you can see where the bottlenecks are along the way if your network
communication is stalling.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 120
Introduction to Linux (CSP3213)
b) Browsers: Firefox is the default web browser in Ubuntu. It is a lightweight web browser
based on Mozilla and offers the following features:
 Tabbed Browsing - open multiple pages within the same window
 Pop-Up Blocking - blocks pop-up advertising windows
 Search Bar - perform searches on a large number of sites without extra software
 Standards Support - strongly adheres to web standards
 Look-and-Feel Customisation - supports themes and addons

Browsers can be classified as graphical and non-graphical. Following are a few browsers
used in Linux:

1. Chromium is the open-source version of Chrome. Chromium is available from the


Universe repository, as package name chromium-browser. To install it, open the
Terminal and enter sudo apt-get install chromium-browser.

2. Chrome is Google's web browser that is meant to be simple, extensible and fast. As
well, you can use extensions like in Firefox.

3. Konqueror is KDE's advanced file manager, web browser and document viewer.
Konqueror is an open source web browser that supports the current web standards.

4. Opera is a web browser developed by Opera Software.

5. Dillo is a lightweight and fast Internet browser. It does not have as many features as
some of the other browsers listed here but it is well-suited for older computers that
do not have enough speed or memory to run a full-featured browser.

6. Epiphany is a simple yet powerful web browser developed by the GNOME


community. Its principles are simplicity and standards compliance. Simplicity is
achieved by a well designed user interface which closely integrates with the GNOME
desktop. Standards compliance is achieved on the HTML side by using the WebKit
rendering engine; and on the user interface side by closely following the GNOME
Human Interface Guidelines (HIG).

7. Lynx is a character-based web browser that can be run inside a terminal or on the
console.

8. Links is a browser that may be be run in either text mode, or graphical mode.

9. ELinks is an advanced text-mode browser.

10. Midori is a fast, lightweight graphical web browser based on WebKit. Often used
with the Xfce desktop environment.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 121
Introduction to Linux (CSP3213)
c) Transferring files:
Following steps can be followed to transfer files between two machines:
1. To get started, right-click on the folder you wish to share and select ‘Sharing Options’

2. When prompted to install Samba services, do it.

3. After installing Samba services, click ‘Restart session’

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 122
Introduction to Linux (CSP3213)

4. Then click ‘Create Share’ to complete the process

5. Open Terminal Replace USERNAME with your account name.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 123
Introduction to Linux (CSP3213)
sudo smbpasswd -a USERNAME

On the Windows machine, go to Start –> All Programs –> Accessories –> run and type the
command:
\\computer_name\share_name

computer name can be ip address of ubuntu machine , to check ip of ubuntu machine , go to


ubuntu machine & open terminal & type ifconfig

6. Type the Ubuntu computer name and the share name of the resource. You will get a
prompted to enter your credentials. Type your Ubuntu username and password and click
‘OK’

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 124
Introduction to Linux (CSP3213)
7. Now try again to access the shares from your Windows machine.

Learning Outcome:

 Explain many basic networking concepts including types of networks and addressing
issues.

 Know how to configure network interfaces and use basic networking utilities, such
as ifconfig, ip, ping, route& traceroute.

 Use graphical and non-graphical browsers, such


as Lynx, w3m,Firefox, Chrome and Epiphany.

 Transfer files to and from clients and servers using both graphical and text mode
applications, such as Filezilla, ftp, sftp, curl and wget.

Viva Questions

 Dump the network traffic for analysis purposes.


 Monitor the network traffic in text mode.
 What are IPv4 addresses?
 What do you mean by Net ID and Host ID?
 What is the purpose of the wget command?
 What is the purpose of the ftp command?
 Give the steps for transferring of files.
 What is the purpose of traceroute command?

ACTIVITY FOR THE STUDENTS

 Practice the Lab exercises for Networking Operations, Chapter 12 of your edx
course.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 125
Introduction to Linux (CSP3213)

Program 22
Aim: Process Oriented Commands:

For this purpose Use this Command Examples*


To see currently running process ps $ ps
To stop any process by PID i.e. to
kill {PID} $ kill 1012
kill process
To stop processes by name i.e. to
killall {Process-name} $ killall httpd
kill process
To get information about all
ps -ag $ ps -ag
running process
To stop all process except your
kill 0 $ kill 0
shell
For background processing (With
&, use to put particular
linux-command & $ ls / -R | wc -l &
command and program in
background)
To display the owner of the
processes along with the ps aux $ ps aux
processes
For e.g. you want to see
To see if a particular process is whether Apache web
running or not. For this purpose server process is running
ps ax | grep process-U-want-
you have to use ps command in or not then give
to see
combination with the grep command
command
$ ps ax | grep httpd

To see currently running


top $ top
processes and other information
Displays the processes
like memory and CPU usage with
dynamically Note that to exit from top
real time updates.
command press q.
To display a tree of processes pstree $ pstree

Learning Outcome:

 Describe what a process is and distinguish between types of processes.

 Enumerate process attributes.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 126
Introduction to Linux (CSP3213)
 Manage processes using ps and top.

 Understand the use of load averages and other process metrics.

 Manipulate processes by putting them in background and restoring them


to foreground.

 Use at, cron, and sleep to schedule processes in the future or pause them.

Viva Questions

 Give the command to output the processes in tree format.


 List the processes
 List the processes in long format.
 List the processes dynamically.
 What is the key combination to interrupt a process
 Give the signals used to interrupt a process
 What is the purpose of killall command
 Use the kill command to hangup a process.
 Use the kill command to continue a paused process.
 CTRL+Z key combination is used for what purpose?

ACTIVITY FOR THE STUDENTS

 Create a job that writes the date to an output file thrice, with a gap of 60 seconds
and 180 seconds. Check whether the job is running and bring it to foreground job.
Stop the foreground job and make it run in the background. Finally, kill the
background job and verify its status.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 127
Introduction to Linux (CSP3213)

Program 23
Aim: Process Scheduling Commands

Linux and Unix provides sophisticated facilities to schedule a job to run at a specified time of
day.
The commands used for the purpose are:

1 at: One time execution


Syntax: $ at 13:01
at > emp.sh
[Ctrl-d]
Description: at takes as its arguments the time the job is to be executed and displays the
at> prompt. Input has to be supplied from the standard input.

At allows fairly complex time specifications, extending the POSIX.2 standard. It accepts
times of the form HH:MM to run a job at a specific time of day. (If that time is already past,
the next day is assumed.) You may also specify midnight, noon, or teatime (4pm) and you
can have a time-of-day suffixed with AM or PM for running in the morning or the evening.
You can also say what day the job will be run, by giving a date in the form month-
name day with an optional year, or giving a date of the
form MMDDYY or MM/DD/YY or DD.MM.YY. The specification of a date must follow the
specification of the time of day. You can also give times like now + count time-units, where
the time-units can be minutes, hours, days, or weeks and you can tell at to run the job
today by suffixing the time with today and to run the job tomorrow by suffixing the time
with tomorrow.

For example, to run a job at 4pm three days from now, you would do at 4pm + 3 days, to
run a job at 10:00am on July 31, you would do at 10am Jul 31 and to run a job at 1am
tomorrow, you would do at 1am tomorrow.

OPTIONS

-V: prints the version number to standard error.


-q queue: uses the specified queue. A queue designation consists of a single letter; valid
queue designations range from a to z. and A to Z. The a queue is the default for at and
the b queue for batch. Queues with higher letters run with increased niceness. The special
queue "=" is reserved for jobs which are currently running. If a job is submitted to a queue
designated with an uppercase letter, it is treated as if it had been submitted to batch at
that time. If atq is given a specific queue, it will only show jobs pending in that queue.

-m: Send mail to the user when the job has completed even if there was no output.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 128
Introduction to Linux (CSP3213)

-f file: Reads the job from file rather than standard input.

-l: Is an alias for atq.

-d: Is an alias for atrm.

-v: Shows the time the job will be executed. Times displayed will be in the format "1997-02-
20 14:50" unless the environment variable POSIXLY_CORRECT is set; then, it will be "Thu
Feb 20 14:50:00 1996".
-c: cats the jobs listed on the command line to standard output.

2. cron: Running Jobs Periodically

crontab - tables for driving cron

DESCRIPTION

A crontab file contains instructions to the cron(8) daemon of the general form: ``run this
command at this time on this date''. Each user has their own crontab, and commands in any
given crontab will be executed as the user who owns the crontab. Uucp and News will
usually have their own crontabs, eliminating the need for explicitly running su(1) as part of a
cron command.

EXAMPLE CRON FILE

# use /bin/sh to run commands, no matter what /etc/passwd says

SHELL=/bin/sh

# mail any output to `paul', no matter whose crontab this is

MAILTO=paul

# run five minutes after midnight, every day

50*** $HOME/bin/daily.job >> $HOME/tmp/out 2>&1

# run at 2:15pm on the first of every month -- output mailed to paul

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 129
Introduction to Linux (CSP3213)
15 14 1 * * $HOME/bin/monthly

# run at 10 pm on weekdays, annoy Joe

0 22 * * 1-5 mail -s "It's 10pm" joe%Joe,%%Where are your kids?%

23 0-23/2 * * * echo "run 23 minutes after midn, 2am, 4am ..., everyday"

5 4 * * sun echo "run at 5 after 4 every sunday"

Learning Outcome:

Processes can be scheduled to run without any human intervention.

VIVA QUESTIONS

 What server processes get initialized during system startup and then wait for a user
or system request indicating that their service is required?
 Give an example of processes that are scheduled to run but are then disconnected
form the terminal.
 Give all the possible states of processes.
 What do you mean by niceness?
 What is the unique identifier of a process?
 What is the symbol for a low priority process?
 What is the symbol for a high priority process?
 Where is the crontab file located?

ACTIVITY FOR THE STUDENTS

 Create job using at to back up files in one directory to another 10 minutes from now.
 Set up a cron job to backup the files in one directory to another every day at 10 am.
Put the commands in file called mycron.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 130
Introduction to Linux (CSP3213)

Program 24
Aim: Regular Expressions, Redirections and Filters in Linux.

1. more: more - file perusal filter for crt viewing

SYNOPSIS

more [-dlfpcsu ] [-num ] [+/ pattern] [+ linenum] [file ... ]

DESCRIPTION

More is a filter for paging through text one screenful at a time. This version is especially
primitve. Users should realize that less(1) provides more(1) emulation and extensive
enhancements.

OPTIONS

Command line options are described below. Options are also taken from the environment
variableMORE (make sure to precede them with a dash (``-'')) but command line options will
override them.

-num: This option specifies an integer which is the screen size (in lines).
-d: more will prompt the user with the message "[Press space to continue, 'q' to quit.]" and
will display "[Press 'h' for instructions.]" instead of ringing the bell when an illegal key is
pressed.

-l: more usually treats ^L (form feed) as a special character, and will pause after any line that
contains a form feed. The -l option will prevent this behavior.

-f: Causes more to count logical, rather than screen lines (i.e., long lines are not folded).

-p: Do not scroll. Instead, clear the whole screen and then display the text.

-c: Do not scroll. Instead, paint each screen from the top, clearing the remainder of each line
as it is displayed.

-s: Squeeze multiple blank lines into one.

-u: Suppress underlining.

2. wc, or "word count,": prints a count of newlines, words, and bytes for each input file.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 131
Introduction to Linux (CSP3213)
Syntax: wc [Options]…[FILE]…

Description:
wc prints newline, word, and byte counts for each FILE, and a total if more than oneFILE is
specified. With no FILE, or when FILE is a dash ("-"), wc operates on standard input. (A word
is a non-zero-length sequence of characters delimited by white space.)

The options below may be used to select which counts are printed. Counts are always in the
following order: newline, word, character, byte, maximum line length.

Options:

-c, --bytes print the byte counts.


-m, --chars print the character counts.
-l, --lines print the newline counts.
--files0- read input from the files specified by NUL-terminated names in file F;
from=F
-L, --max- print the length of the longest line.
line-length
-w, --words print the word counts.
--help display a help message, and exit.
--version output version information, and exit.

3. diff: analyzes two files and prints the lines that are different. Essentially, it outputs a set
of instructions for how to change one file in order to make it identical to the second file.
It does not actually change the files; however, it can optionally generate a script (with the -
e option) for the program ed (or ex which can be used to apply the changes.

Syntax: diff file1.txt file2.txt

4. sort: sorts lines of text files

SYNOPSIS

sort [OPTION]... [FILE]...

DESCRIPTION

Write sorted concatenation of all FILE(s) to standard output.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 132
Introduction to Linux (CSP3213)
Ordering options:

Mandatory arguments to long options are mandatory for short options too.

-b, --ignore-leading-blanks ignore leading blanks


-d, --dictionary-order- consider only blanks and alphanumeric characters
-f, --ignore-case- fold lower case to upper case characters

-g, --general-numeric-sort- compare according to general numerical value

-i, --ignore-nonprinting-consider only printable characters

-M, --month-sort- compare (unknown) < `JAN' < ... < `DEC'

5. uniq - remove duplicate lines from a sorted file

SYNOPSIS

uniq [OPTION]... [INPUT [OUTPUT]]

DESCRIPTION

Discard all but one of successive identical lines from INPUT (or standard input), writing to
OUTPUT (or standard output).Mandatory arguments to long options are mandatory for
short options too.

OPTIONS
-c, --count: prefix lines by the number of occurrences
-d, --repeated : only print duplicate lines

-D, --all-repeated[=delimit-method] print all duplicate lines: delimit-


method={none(default),prepend,separate} Delimiting is done with blank lines.

-f, --skip-fields=N: avoid comparing the first N fields

-i, --ignore-case: ignore differences in case when comparing

6. grep, egrep, fgrep - print lines matching a pattern


SYNOPSIS

grep [options] PATTERN [FILE...]


grep [options] [-e PATTERN | -f FILE] [FILE...]

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 133
Introduction to Linux (CSP3213)
DESCRIPTION

Grep searches the named input FILEs (or standard input if no files are named, or the file
name - is given) for lines containing a match to the given PATTERN. By default, grep prints
the matching lines.

In addition, two variant programs egrep and fgrep are available. Egrep is the same as grep -
E.Fgrep is the same as grep -F.

OPTIONS

-A NUM, --after-context=NUM
Print NUM lines of trailing context after matching lines. Places a line containing --
between contiguous groups of matches.

-a, --text

Process a binary file as if it were text; this is equivalent to the --binary-


files=text option.

-B NUM, --before-context=NUM

Print NUM lines of leading context before matching lines. Places a line containing --
between contiguous groups of matches.

-C NUM, --context=NUM
Print NUM lines of output context. Places a line containing -- between contiguous
groups of matches.

-b, --byte-offset
Print the byte offset within the input file before each line of output.

Redirection Operators:

Redirection is one of Unix's strongest points. Ramnick explains this concept in this article. He
talks about Input, Output Redirection. He cites many simple and useful ways in which we
can put redirection to good use.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 134
Introduction to Linux (CSP3213)

Introduction

For those of you'll who have no idea what Redirection means, let me explain it in a few
words. Whenever you run a program you get some output at the shell prompt. In case
youdon't want that output to appear in the shell window, you can redirect it elsewhere. you
can make the output go into a file...or maybe go directly to the printer.. or you could make it
disappear :)

This is known as Redirection. Not only can the output of programs be redirected, you can
also redirect the input for programs. I shall be explaining all this in detail in this article. Lets
begin...

File Descriptors

One important thing you have to know to understand Redirection is file descriptors. In Unix
every file has a no. associated with it called the file descriptor. And in Unix everything is a
file. Right from your devices connected to your machine to the normal text files storing
some information - all of these are looked at, as files by the Operating System.

Similarly even your screen on which your programs display their output are files for Unix.
These have file descriptors associated with it. So when a program actually executes it sends
its output to this file descriptor and since this particular file descriptor happens to be
pointing to the screen, the output gets displayed on the screen. Had it been the file
descriptor of the printer, the output would have been printed by the printer. (There are
ofcourse other factors which come into play, but I guess you got the idea of how everything
is a file and you send whatver you want to particular files descriptors)

Whenever any program is executed (i.e. when the user types a command) the program has
3 important files to work with. They are standard input, standard output, and standard
error. These are 3 files that are always open when a program runs. You could kind of
consider them to be inherently present for all programs (For the techies.. basically when a
child process is forked from a parent process, these 3 files are made available to the child
process). For the rest, just remember that you always have these 3 files with you whenever
you type any command at the prompt. As explained before a file descriptor, is associated
with each of these files -

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 135
Introduction to Linux (CSP3213)

File
Descriptor Points to -
Descriptor
0 Standard Input (Generally Keyboard)
1 Standard output (Generally Display/Screen)
2 Standard Error Ouput (Generally Display/Screen)

You could redirect any of these files to other files. In short if you redirect 1 (standard
output) to the printer, your programs output would start getting printed instead of being
displayed on the screen.

What is the standard input? That would be your keyboard. Most of the times since you
enter commands with your keyboard; you could consider 0 to be your keyboard. Since you
get the output of your command on the screen, 1 would be the screen (display) and the
errors as well are shown on the screen to you, so 2 would also be the screen.

For those of you'll who like to think ahead of what is being discussed... you'll must have
already understood that you can now avoid all those irritating, irrelevant error messages
you often get while executing some programs. You could just redirect the standard error (2)
to some file and avoid seeing the error messages on the screen!!

Output Redirection

The most common use of Redirection is to redirect the output (that normally goes to the
terminal) from a command to a file instead. This is known as Output Redirection. This is
generally used when you get a lot of output when you execute your program. Often you see
that screens scroll past very rapidly. You could get all the output in a file and then even
transfer that file elsewhere or mail it to someone.

The way to redirect the output is by using the ' > ' operator in shell command you enter. This
is shown below. The ' > ' symbol is known as the output redirection operator. Any command
that outputs its results to the screen can have its output sent to a file.

$ ls > listing

The ' ls ' command would normally give you a directory listing. Since you have the ' > '
operator after the ' ls ' command, redirection would take place. What follows the ' > ' tells
Unix where to redirect the output. In our case it would create a file named ' listing ' and
write the directory listing in that file. You could view this file using any text editor or by
using the cat command.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 136
Introduction to Linux (CSP3213)
Note: If the file mentioned already exists, it is overwritten. So care should be taken to enter
a proper name. In case you want to append to an existing file, then instead of the ' > '
operator you should use the ' >> ' operator. This would append to the file if it already exists,
else it would create a new file by that name and then add the output to that newly created
file.

Input Redirection

Input Redirection is not as popular as Output Redirection. Since most of the times you
would expect the input to be typed at the keyboard. But when it is used effectively, Input
Redirection can be of great use. The general use of Input Redirection is when you have some
kind of file, which you have ready and now you would like to use some command on that
file.

You can use Input Redirection by typing the ' < ' operator. An excellent example of Input
Redirection has been shown below.

$ mail cousin < my_typed_letter

The above command would start the mail program with contents of the file named '
my_typed_letter ' as the input since the Input Redirection operator was used.

Note: You can't have Input Redirection with any program/command. Only those commands
that accept input from keyboard could be redirected to use some kind of text files as their
input. Similarly Output Redirection is also useful only when the program sends its output to
the terminal. In case you are redirecting the output of a program that runs under X, it would
be of no use to you.

Error Redirection

This is a very popular feature that many Unix users are happy to learn. In case you have
worked with Unix for some time, you must have realised that for a lot of commands you
type you get a lot of error messages. And you are not really bothered about those error
messages. For example whenever I perform a search for a file, I always get a lot
ofpermission denied error messages. There may be ways to fix those things. But the simplest
way is to redirect the error messages elsewhere so that it doesn't bother me. In my case I
know that errors I get while searching for files would be of no use to me.

Here is a way to redirect the error messages

$ myprogram 2>errorsfile

This above command would execute a program named ' myprogram ' and whatever errors
are generated while executing that program would all be added to a file named ' errorsfile '

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 137
Introduction to Linux (CSP3213)
rather than be displayed on the screen. Remember that 2 is the error output file descriptor.
Thus ' 2> ' means redirect the error output.

$ myprogram 2>>all_errors_till_now

The above command would be useful in case you have been saving all the error messages
for some later use. This time the error messages would append to the file rather than create
a new file.

You might realize that in the above case since I wasn't interested in the error messages
generated by the program I redirected the output to a file. But since those error messages
don't interest me I would have to go and delete that file created every time I run that
command. Else I would have several such files created all over whenever I redirect my
unwanted error output. An excellent way around is shown below

$ find / -name s*.jpg 2>/dev/null

What's /dev/null ????? That something like a black hole. Whatever is sent to the ' /dev/null '
never returns. Neither does one know where it goes. It simple disappears. Isn't that fantastic
!! So remember.. whenever you want to remove something.. something that you don't want
...you could just send it to /dev/null

Different ways to use Redirection Operators

Suppose you want to create a text file quickly

$ cat > filename


This is some text that I want in this file
^D

That's it!! Once you type the ' cat ' command, use the Redirection operator and add a name
for a file. Then start typing your line. And finally press Ctrl+D. You will have a file named '
filename ' in the same directory.

Suppose you want to add a single line to an existing file.

$ echo "this is a new line" >> exsisting_file

That would add the new line to the file named ' existing_file ' . Remember to use ' >> '
instead of ' > ' else you would overwrite the file.

Suppose you wanted to join 2 files

$ cat file2 >> file1

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 138
Introduction to Linux (CSP3213)
The contents of ' file2 ' would be added to ' file1 ' .

Suppose you want to join a couple of files

$ cat file1 file2 > file3

This would add the contents of ' file1 ' and ' file2 ' and then write these contents into a new
file named ' file3 ' .

Redirection works with many commands besides normal ones such as ' cat ' or ' ls ' . One
example I could give you is in case you are programming using any language you could
redirect the output messages of the compilation of your code so that you can view them
later on. There are lots of commands where you can use Redirection. The more you use Unix
the more you will come to know.

Learning Outcome:

General Utilities for redirecting the output to files and applying filters to the output are
learned.

Viva Questions

 What command will you use if you want to combine the contents of file1 and file2
in file3.
 Give the symbol for redirection operator.
 Give the symbol for redirection operator to append data to already created files.
 How can you redirect your error messages to file named errorsfile?
 What is the purpose of sort command?
 What is the purpose of uniq command?
 What is the purpose of grep command?
 What is the purpose of diff command?
 Give the command to count the number of lines in a file?
 Give the command to count the number of words and characters in a file?

ACTIVITY FOR THE STUDENTS

 Create a file file_home having a list of all the files available in your home directory.
 Create a file filez in your home directory, now append this file name to the file
created earlier, file_home.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 139
Introduction to Linux (CSP3213)

Program 25
Aim: Bash Shell Scripting:

a) Features and Capabilities


A shell is a command line interpreter which provides the user interface for terminal
windows. It can also be used to run scripts, even in non-interactive sessions without a
terminal window, as if the commands were being directly typed in. Shell scripting provides
following features and capabilities.

Command Shell Choices


The command interpreter is tasked with executing statements that follow it in the script.
Commonly used interpreters include: /usr/bin/perl, /bin/bash, /bin/csh,
/usr/bin/python and /bin/sh.
Typing a long sequence of commands at a terminal window can be complicated, time
consuming, and error prone. By deploying shell scripts, using the command-line becomes an
efficient and quick way to launch complex sequences of steps. The fact that shell scripts are
saved in a file also makes it easy to use them to create new script variations and share
standard procedures with several users.
Linux provides a wide choice of shells; exactly what is available on the system is listed in
/etc/shells. Typical choices are:
/bin/sh
/bin/bash
/bin/tcsh

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 140
Introduction to Linux (CSP3213)
/bin/csh
/bin/ksh

Most Linux users use the default bash shell, but those with long UNIX backgrounds with
other shells may want to override the default.

b) Syntax

Scripts require you to follow standard language syntax. Rules delineate how to define
variables and how to construct and format allowed statements, etc. The table lists some
special character usages within bash scripts:

Character Description
Used to add a comment, except when used as \#, or
#
as #! when starting a script
Used at the end of a line to indicate continuation on
\
to the next line
; Used to interpret what follows as a new command
$ Indicates what follows is a variable

Note that when # is inserted at the beginning of a line of commentary, the whole line is
ignored.
# This line will not get executed.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 141
Introduction to Linux (CSP3213)
c) Constructs using expr
Arithmetic expressions can be evaluated in the following three ways (spaces are
important!):
 Using the expr utility: expr is a standard but somewhat deprecated program. The
syntax is as follows:

expr 8 + 8
echo $(expr 8 + 8)
 Using the $((...)) syntax: This is the built-in shell format. The syntax is as follows:

echo $((x+1))
 Using the built-in shell command let. The syntax is as follows:

let x=( 1 + 2 ); echo $x


In modern shell scripts the use of expr is better replaced with var=$((...))

d) Simulating an array using eval

One of the more under-appreciated commands in shell scripting is the eval builtin. The eval
builtin takes a series of arguments, concatenates them into a single command, then
executes it. For example, the following script assigns the value 3 to the variable X and then
prints the value:

#!/bin/sh

eval X=3

echo $X

For such simple examples, the eval builtin is superfluous. However, the behavior of the eval
builtin becomes much more interesting when you need to construct or choose variable
names programmatically. For example, the next script also assigns the value 3 to the
variable X:

#!/bin/sh

VARIABLE="X"

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 142
Introduction to Linux (CSP3213)
eval $VARIABLE=3

echo $X

When the eval builtin evaluates its arguments, it does so in two steps. In the first step,
variables are replaced by their values. In the preceding example, the letter X is inserted in
place of $VARIABLE. Thus, the result of the first step is the following string:

X=3

In the second step, the eval builtin executes the statement generated by the first step, thus
assigning the value 3 to the variable X. As further proof, the echo statement at the end of
the script prints the value 3.
The eval builtin can be particularly convenient as a substitute for arrays in shell script
programming. It can also be used to provide a level of indirection.
The script below uses eval by creating a series of variables to hold the values of a simulated
array.

#!/bin/sh

COUNTER=0

VALUE="-1"

echo "Enter a series of lines of test. Enter a blank line to end."

while [ "x$VALUE" != "x" ] ; do

read VALUE

eval ARRAY_$COUNTER=$VALUE

eval export ARRAY_$COUNTER

COUNTER=$(expr $COUNTER '+' 1) # More on this in Paint by Numbers

done

COUNTER=$(expr $COUNTER '-' 1) # Subtract one for the blank value at the end.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 143
Introduction to Linux (CSP3213)

# print the exported variables.

COUNTERB=0;

echo "Printing values."

while [ $COUNTERB -lt $COUNTER ] ; do

echo "ARRAY[$COUNTERB] = $(eval echo "$"ARRAY_$COUNTERB)"

COUNTERB=$(expr $COUNTERB '+' 1) # More on this in Paint by Numbers

done
This same technique can be used for splitting an unknown number of input values in a single
line as shown in the next listing:
#!/bin/sh

COUNTER=0

VALUE="-1"

echo "Enter a series of lines of numbers separated by spaces."

read LIST

IFS=" "

for VALUE in $LIST ; do

eval ARRAY_$COUNTER=$VALUE

eval export ARRAY_$COUNTER

COUNTER=$(expr $COUNTER '+' 1) # More on this in Paint by Numbers

done

# print the exported variables.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 144
Introduction to Linux (CSP3213)
COUNTERB=0;

echo "Printing values."

while [ $COUNTERB -lt $COUNTER ] ; do

echo "ARRAY[$COUNTERB] = $(eval echo '$'ARRAY_$COUNTERB)"

COUNTERB=$(expr $COUNTERB '+' 1) # More on this in Paint by Numbers

done

Learning Outcome:

 Explain the features and capabilities of bash shell scripting.

 Know the basic syntax of scripting statements.

 Be familiar with various methods and constructs used.

 Know how to test for properties and existence of files and other objects.

 Perform arithmetic operations using scripting language.

Viva Questions

 What command makes the script, script1.sh executable?


 Which of the following commands is used to manually pass a text file, script.sh, to
the shell interpreter?
 Give the character that is used to represent the continuation of commands over
several lines.
 Give the different types of commands that can be used in bash shell script.
 Give the command that provide computational capabilities to the shell?
 What are the features of expr command?
 Echo command is used for what purpose?
 Eval command is used for what purpose?

ACTIVITY FOR THE STUDENTS

Write a script that does ls for a nonexistent file, followed by display of the exit status
code. Then create a file and display the new exit status code. In each task, send the ls
output to /dev/null.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 145
Introduction to Linux (CSP3213)
Program 26

Aim: Write Script to find out biggest number from given three nos. No’s are supplied as
command line argument. Print error if sufficient arguments are not supplied

Shell Variables are an integral part of shell programming. They provide ability to store and
manipulate information within a shell program.

The rules for building shell variables are as follows:


1. A variable name is any combination of alphabets, digits and an underscore.
2. No commas or blanks are allowed.
3. The first character of a variable name must be either an alphabet or an underscore.
4. Variables names should be of any reasonable length.

Answer:#!/bin/bash
# Algo:
# 1) START: Take three nos as n1,n2,n3.
# 2) Is n1 is greater than n2 and n3, if yes
# print n1 is bigest no goto step 5, otherwise goto next step
# 3) Is n2 is greater than n1 and n3, if yes
# print n2 is bigest no goto step 5, otherwise goto next step
# 4) Is n3 is greater than n1 and n2, if yes
# print n3 is bigest no goto step 5, otherwise goto next step
# 5) END

if [ $# -ne 3 ]
then
echo "$0: number1 number2 number3 are not given" >&2
exit 1
fi
n1=$1
n2=$2
n3=$3
if [ $n1 -gt $n2 ] && [ $n1 -gt $n3 ]
then
echo "$n1 is Biggest number"
elif [ $n2 -gt $n1 ] && [ $n2 -gt $n3 ]
then
echo "$n2 is Biggest number"
elif [ $n3 -gt $n1 ] && [ $n3 -gt $n2 ]
then
echo "$n3 is Biggest number"
elif [ $1 -eq $2 ] && [ $1 -eq $3 ] && [ $2 -eq $3 ]
then

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 146
Introduction to Linux (CSP3213)
echo "All the three numbers are equal"
else
echo "I cannot figure out which number is bigger"
fi

Output:
n1= 10
n2= 200
n3= 4
n2 is the biggest number

Viva Questions
 How can you change the $ prompt to your name?
 What are keywords?
 What is the difference between variable names and keywords?
 How can you make a variable value to remain unchanged?
 Give the syntax for if-else loop.
 What are conditional statements?
 What does $1 specify?
 Give the command to display the number of arguments passed.

ACTIVITY FOR THE STUDENTS

Indicate whether the following variable names are valid or invalid. If invalid, state the reason
for the same.

I. Number of years
II. Si-int
III. AVERAGE
IV. 458
V. Expr
VI. @abc

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 147
Introduction to Linux (CSP3213)
Program 27
Aim: Advanced Bash Shell Scripting:

String Manipulation:

A string variable contains a sequence of text characters. It can include letters, numbers,
symbols and punctuation marks. Some examples: abcde, 123, abcde 123, abcde-123,
&acbde=%123

String operators include those that do comparison, sorting, and finding the length. The
following table demonstrates the use of some basic string operators.

Operator Meaning

[[ string1 > string2 ]] Compares the sorting order of string1 and string2.

[[ string1 == string2 ]] Compares the characters in string1 with the characters in


string2.

myLen1=${#string1} Saves the length of string1 in the variable myLen1.

At times, you may not need to compare or use an entire string. To extract the first character
of a string we can specify:

${string:0:1} Here 0 is the offset in the string (i.e., which character to begin from) where the
extraction needs to start and 1 is the number of characters to be extracted.

To extract all characters in a string after a dot (.), use the following expression: ${string#*.}

Boolean Expressions:

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 148
Introduction to Linux (CSP3213)
Boolean expressions evaluate to either TRUE or FALSE, and results are obtained using
the various Boolean operators listed in the table.

Operator Operation Meaning

&& AND The action will be performed only if both the conditions
evaluate to true.

|| OR The action will be performed if any one of the conditions


evaluate to true.

! NOT The action will be performed only if the condition evaluates


to false.

Note that if you have multiple conditions strung together with the && operator processing
stops as soon as a condition evaluates to false. For example if you have A && B && C and A
is true but B is false, C will never be executed.

Likewise if you are using the || operator, processing stops as soon as anything is true. For
example if you have A || B || Cand A is false and B is true, you will also never execute C.

Tests in Boolean Expression:

Boolean expressions return either TRUE or FALSE. We can use such expressions when
working with multiple data types including strings or numbers as well as with files. For
example, to check if a file exists, use the following conditional test:

[ -e <filename> ]

Similarly, to check if the value of number1 is greater than the value of number2, use the
following conditional test:

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 149
Introduction to Linux (CSP3213)

[ $number1 -gt $number2 ]

The operator -gt returns TRUE if number1 is greater thannumber2.

Case Structure:

The case statement is used in scenarios where the actual value of a variable can lead to
different execution paths. Case statements are often used to handle command-line options.

Below are some of the advantages of using the case statement:

 It is easier to read and write.

 It is a good alternative to nested, multi-level if-then-else-fi code blocks.

 It enables you to compare a variable against several values at once.

 It reduces the complexity of a program.

case expression in
pattern1) execute commands;;
pattern2) execute commands;;
pattern3) execute commands;;
pattern4) execute commands;;
*) execute some default commands or nothing ;;
esac

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 150
Introduction to Linux (CSP3213)

Debugging:

While working with scripts and commands, you may run into errors. These may be due to an
error in the script, such as incorrect syntax, or other ingredients such as a missing file or
insufficient permission to do an operation. These errors may be reported with a specific
error code, but often just yield incorrect or confusing output. So how do you go about
identifying and fixing an error?

Debugging helps you troubleshoot and resolve such errors, and is one of the most
important tasks a system administrator performs

Before fixing an error (or bug), it is vital to know its source.

In bash shell scripting, you can run a script in debug mode by doing bash –x ./script_file.
Debug mode helps identify the error because:

 It traces and prefixes each command with the + character.

 It displays each command before executing it.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 151
Introduction to Linux (CSP3213)
 It can debug only selected parts of a script (if desired) with:
set -x # turns on debugging
...
set +x # turns off debugging
 Redirecting Errors to File and Screen

 In UNIX/Linux, all programs that run are given three open file streams when they are
started as listed in the table:

File stream Description File Descriptor

Stdin Standard Input, by default the keyboard/terminal 0


for programs run from the command line

Stdout Standard output, by default the screen for 1


programs run from the command line

Stderr Standard error, where output error messages are 2


shown or saved

 Using redirection we can save the stdout and stderr output streams to one file or
two separate files for later analysis after a program or command is executed

 On the left screen is a buggy shell script. On the right screen the buggy script is
executed and the errors are redirected to the file"error.txt". Using "cat" to display
the contents of "error.txt" shows the errors of executing the buggy shell script
(presumably for further debugging).

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 152
Introduction to Linux (CSP3213)

Learning Outcome:

 Manipulate strings to perform actions such as comparison and sorting.

 Use Boolean expressions when working with multiple data types including strings or
numbers as well as files.

 Use case statements to handle command line options.

 Use looping constructs to execute one or more lines of code repetitively.

 Debug scripts using set -x and set +x.

 Create temporary files and directories.

 Create and use random numbers.

Viva Questions

 How do you represent the NOT operator?


 What are the different types of looping constructs available?
 Which of the looping constructs repeats a set of statements as long as the control
command returns a true exit status?
 Which of the following looping constructs repeats a set of statements for a known
number of iterations?
 What are the Boolean expressions available?
 What do you mean by debugging?
 What is the purpose of stdout?
 What are the commands set+x and set-x used for?

ACTIVITY FOR THE STUDENTS

Write a script that takes exactly one argument, a directory name. The script should print
that argument back to standard output. Make sure the script generates a usage message if
needed and that it handles errors with a message.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 153
Introduction to Linux (CSP3213)
Program 28
Aim: Write Script, using case statement to perform basic math operation as
follows
+ addition
- subtraction
x multiplication
/ division

The case statement is used in scenarios where the actual value of a variable can lead to
different execution paths. Casestatements are often used to handle command-line options.

Below are some of the advantages of using the case statement:

 It is easier to read and write.

 It is a good alternative to nested, multi-level if-then-else-fi code blocks.

 It enables you to compare a variable against several values at once.

 It reduces the complexity of a program.

Answer:
#!/bin/bash

if test $# = 3
then
case $2 in
+) let z=$1+$3;;
-) let z=$1-$3;;
/) let z=$1/$3;;
x|X) let z=$1*$3;;
*) echo Warning - $2 invalid operator, only +,-,x,/ operator allowed
exit;;
esac
echo Answer is $z
else
echo "Usage - $0 value1 operator value2"
echo " Where, value1 and value2 are numeric values"
echo " operator can be +,-,/,x (For Multiplication)"
fi

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 154
Introduction to Linux (CSP3213)
Learning Outcome:

To make use of if-then-else and case statement to control the execution of statements.

Viva Questions
 What terms signify the beginning and end of if block in if-then-else?
 What terms signify the beginning and end of else block in if-then-else?
 What is CASE statement?
 When is CASE preferred over if-then-else?
 What is $# used for?
 Give the structure for CASE statement.
 Give the advantages for case statement
 What do you mean by shell scripting?

ACTIVITY FOR THE STUDENTS

An integer is input through keyboard. Write a shell script to find out whether it is an odd
number or even number.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 155
Introduction to Linux (CSP3213)
Program 29
Aim: Write script to print given numbers sum of all digit, For eg. If no is 123 it's sum of all
digit will be 1+2+3 = 6.

Answer: #!/bin/bash
# Algo:
# 1) Input number n
# 2) Set sum=0, sd=0
# 3) Find single digit in sd as n % 10 it will give (left most digit)
# 4) Construct sum no as sum=sum+sd
# 5) Decrment n by 1
# 6) Is n is greater than zero, if yes goto step 3, otherwise next step
# 7) Print sum
#
if [ $# -ne 1 ]
then
echo "Usage: $0 number"
echo " I will find sum of all digit for given number"
echo " For eg. $0 123, I will print 6 as sum of all digit (1+2+3)"
exit 1
fi

n=$1
sum=0
sd=0
while [ $n -gt 0 ]
do
sd=`expr $n % 10`
sum=`expr $sum + $sd`
n=`expr $n / 10`
done
echo "Sum of digits for given number is $sum"

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 156
Introduction to Linux (CSP3213)

Learning Outcome:
Makes use of if else statement and looping construct (do while).

VIVA QUESTIONS

 In what situations you will prefer the use of while loop over for loop?
 What does the keyword fi signify?
 What terms signify the beginning and end of if block in if-then-else?
 What terms signify the beginning and end of else block in if-then-else?
 What is CASE statement?
 When is CASE preferred over if-then-else?
 What is $# used for?
 Give the structure for CASE statement.
 Give the advantages for case statement

ACTIVITY FOR THE STUDENTS

Write a script to check if the entered number is even or odd?

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 157
Introduction to Linux (CSP3213)
Program 30

Aim: Write shell script to show various system configurations like

1) Currently logged user and their login name


2) Your current shell
3) Your home directory
4) Your operating system type
5) Your current path setting

Answer: #!/bin/bash

nouser=`who | wc -l`
echo -e "User name: $USER (Login name: $LOGNAME)" >> /tmp/info.tmp.01.$$$
echo -e "Current Shell: $SHELL" >> /tmp/info.tmp.01.$$$
echo -e "Home Directory: $HOME" >> /tmp/info.tmp.01.$$$
echo -e "Your O/s Type: $OSTYPE" >> /tmp/info.tmp.01.$$$
echo -e "PATH: $PATH" >> /tmp/info.tmp.01.$$$
echo -e "Current directory: `pwd`" >> /tmp/info.tmp.01.$$$
echo -e "Currently Logged: $nouser user(s)" >> /tmp/info.tmp.01.$$$

if [ -f /etc/redhat-release ]
then
echo -e "OS: `cat /etc/redhat-release`" >> /tmp/info.tmp.01.$$$
fi

if [ -f /etc/shells ]
then
echo -e "Available Shells: " >> /tmp/info.tmp.01.$$$
echo -e "`cat /etc/shells`" >> /tmp/info.tmp.01.$$$
fi

if [ -f /etc/sysconfig/mouse ]
then
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
echo -e "Computer Mouse Information: " >> /tmp/info.tmp.01.$$$
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
echo -e "`cat /etc/sysconfig/mouse`" >> /tmp/info.tmp.01.$$$
fi
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
echo -e "Computer CPU Information:" >> /tmp/info.tmp.01.$$$
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
cat /proc/cpuinfo >> /tmp/info.tmp.01.$$$

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 158
Introduction to Linux (CSP3213)

echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$


echo -e "Computer Memory Information:" >> /tmp/info.tmp.01.$$$
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
cat /proc/meminfo >> /tmp/info.tmp.01.$$$

if [ -d /proc/ide/hda ]
then
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
echo -e "Hard disk information:" >> /tmp/info.tmp.01.$$$
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
echo -e "Model: `cat /proc/ide/hda/model` " >> /tmp/info.tmp.01.$$$
echo -e "Driver: `cat /proc/ide/hda/driver` " >> /tmp/info.tmp.01.$$$
echo -e "Cache size: `cat /proc/ide/hda/cache` " >> /tmp/info.tmp.01.$$$
fi
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
echo -e "File System (Mount):" >> /tmp/info.tmp.01.$$$
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
cat /proc/mounts >> /tmp/info.tmp.01.$$$

if which dialog > /dev/null


then
dialog --backtitle "Linux Software Diagnostics (LSD) Shell Script Ver.1.0" --title "Press
Up/Down Keys to move" --textbox /tmp/info.tmp.01.$$$ 21 70
else
cat /tmp/info.tmp.01.$$$ |more
fi

rm -f /tmp/info.tmp.01.$$$

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 159
Introduction to Linux (CSP3213)

Learning Outcome:

To make use of the bash commands in shell programming and view the system
configurations.

Viva Questions:

 Give the command to display the computer memory information.


 Give the command to display CPU information.
 Give the command to mount the file system.
 What environmental variable is used to display the home folder?
 What environmental variable is used to display the path?
 What environmental variable is used to display the shell being used?
 What command is used to display the present working directory?
 What is the command uname used for?

ACTIVITY FOR THE STUDENTS


Perform the lab exercises at the back of your MOOC course chapter 5 and chapter 6.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 160
Introduction to Linux (CSP3213)

Program 31

Aim: Write script to print no’s as 5,4,3,2,1 using while loop.

Answer: #!/bin/bash
# Algo:
# 1) START: set value of i to 5 (since we want to start from 5, if you
# want to start from other value put that value)
# 2) Start While Loop
# 3) Check, Is value of i is zero, If yes goto step 5 else
# continue with next step
# 4) print i, decement i by 1 (i.e. i=i-1 to goto zero) and
# goto step 3
# 5) END
#
i=5
while test $i != 0
do
echo "$i"
i=`expr $i - 1`
done

Output:
54321

Viva Questions:

 What do you mean by a counter?


 What is the purpose of echo?
 What do you mean by a variable?
 In what situations you will prefer the use of while loop over for loop?
 What does the keyword fi signify?
 What terms signify the beginning and end of if block in if-then-else?
 What terms signify the beginning and end of else block in if-then-else?

ACTIVITY FOR THE STUDENTS

Perform the above program using for loop.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 161
Introduction to Linux (CSP3213)
Program 32

Aim: For loop and its various types.


Write a shell script to find the factorial of a number using for loop.

for loop syntax


Numeric ranges for syntax is as follows:
for VARIABLE in 1 2 3 4 5 .. N
do
command1
command2
commandN
done
OR
for VARIABLE in file1 file2 file3
do
command1 on $VARIABLE
command2
commandN
done
OR
for OUTPUT in $(Linux-Or-Unix-Command-Here)
do
command1 on $OUTPUT
command2 on $OUTPUT
commandN
done

# !/bin/bash
echo "Total no of factorial wants"
read fact

ans=1
counter=0
while [ $fact -ne $counter ]
do
counter=`expr $counter + 1`
ans=`expr $ans \* $counter`
done
echo "Total of factorial is $ans"

output
Total no of factorial wants 5
Total of factorial is 120

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 162
Introduction to Linux (CSP3213)

Viva Questions:
 What are the different types of looping constructs available?
 Give the different ways you can use to initialize the for loop?
 In what situations you will prefer the use of while loop over for loop?
 What does the keyword fi signify?
 What terms signify the beginning and end of if block in if-then-else?
 What terms signify the beginning and end of else block in if-then-else?
 Perform the above program using while loop.
 Give all the syntax for for loop

ACTIVITY FOR THE STUDENTS

Write a script to perform the Fibonacci of the series.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 163
Introduction to Linux (CSP3213)
Program 33

Aim: Shell Script to manipulate file Operations of creating, editing, saving and comparing
files.

Answer: #!/bin/bash
echo -e “ creating file1”>> cat > file1
if [ $# -ne 3 ]
then
echo "$0: number1 number2 number3 are not given" >&2
exit 1
fi
n1=$1
n2=$2
n3=$3
if [ $n1 -gt $n2 ] && [ $n1 -gt $n3 ]
then
echo "$n1 is Biggest number"
elif [ $n2 -gt $n1 ] && [ $n2 -gt $n3 ]
then
echo "$n2 is Biggest number"
elif [ $n3 -gt $n1 ] && [ $n3 -gt $n2 ]
then
echo "$n3 is Biggest number"
elif [ $1 -eq $2 ] && [ $1 -eq $3 ] && [ $2 -eq $3 ]
then
echo "All the three numbers are equal"
else
echo "I cannot figure out which number is bigger"
fi
[Ctrl-C] // To save the file
$ /usr/ sh file1.sh // to execute the file

Learning Outcome:

To use the bash commands in shell programming for creating, editing and manipulation of
files.

VIVA QUESTIONS
 What are the different purposes of cat command?
 What is the command to execute a file?
 What combination of keys is used to save a file?
 What is the key combination to interrupt a process

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 164
Introduction to Linux (CSP3213)
 Give the signals used to interrupt a process
 What is the purpose of killall command
 Use the kill command to hangup a process.
 Use the kill command to continue a paused process.
 CTRL+Z key combination is used for what purpose?

ACTIVITY FOR THE STUDENTS

Write a script performing all the operations (creating, copying, viewing and concatenating)
performed by cat command.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 165
Introduction to Linux (CSP3213)
Program 34
Aim: Write shell script to show various system configurations like

1) Your current working directory


2) Show Currently logged number of users
3) About your OS and version,release number , kernel version
4) Show all available shells
5) Show mouse settings
6) Show computer cpu information like processor type, speed etc
7) Show memory information
8) Show hard disk information like size of hard-disk, cache memory, model etc
9) File system (Mounted)

Answer: #!/bin/bash

nouser=`who | wc -l`
echo -e "User name: $USER (Login name: $LOGNAME)" >> /tmp/info.tmp.01.$$$
echo -e "Current Shell: $SHELL" >> /tmp/info.tmp.01.$$$
echo -e "Home Directory: $HOME" >> /tmp/info.tmp.01.$$$
echo -e "Your O/s Type: $OSTYPE" >> /tmp/info.tmp.01.$$$
echo -e "PATH: $PATH" >> /tmp/info.tmp.01.$$$
echo -e "Current directory: `pwd`" >> /tmp/info.tmp.01.$$$
echo -e "Currently Logged: $nouser user(s)" >> /tmp/info.tmp.01.$$$

if [ -f /etc/redhat-release ]
then
echo -e "OS: `cat /etc/redhat-release`" >> /tmp/info.tmp.01.$$$
fi

if [ -f /etc/shells ]
then
echo -e "Available Shells: " >> /tmp/info.tmp.01.$$$
echo -e "`cat /etc/shells`" >> /tmp/info.tmp.01.$$$
fi

if [ -f /etc/sysconfig/mouse ]
then
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
echo -e "Computer Mouse Information: " >> /tmp/info.tmp.01.$$$
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
echo -e "`cat /etc/sysconfig/mouse`" >> /tmp/info.tmp.01.$$$
fi
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 166
Introduction to Linux (CSP3213)
echo -e "Computer CPU Information:" >> /tmp/info.tmp.01.$$$
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
cat /proc/cpuinfo >> /tmp/info.tmp.01.$$$

echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$


echo -e "Computer Memory Information:" >> /tmp/info.tmp.01.$$$
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
cat /proc/meminfo >> /tmp/info.tmp.01.$$$

if [ -d /proc/ide/hda ]
then
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
echo -e "Hard disk information:" >> /tmp/info.tmp.01.$$$
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
echo -e "Model: `cat /proc/ide/hda/model` " >> /tmp/info.tmp.01.$$$
echo -e "Driver: `cat /proc/ide/hda/driver` " >> /tmp/info.tmp.01.$$$
echo -e "Cache size: `cat /proc/ide/hda/cache` " >> /tmp/info.tmp.01.$$$
fi
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
echo -e "File System (Mount):" >> /tmp/info.tmp.01.$$$
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
cat /proc/mounts >> /tmp/info.tmp.01.$$$

if which dialog > /dev/null


then
dialog --backtitle "Linux Software Diagnostics (LSD) Shell Script Ver.1.0" --title "Press
Up/Down Keys to move" --textbox /tmp/info.tmp.01.$$$ 21 70
else
cat /tmp/info.tmp.01.$$$ |more
fi

rm -f /tmp/info.tmp.01.$$$

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 167
Introduction to Linux (CSP3213)

Learning Outcome:

System Configuration commands to be used in shell programming.

Viva Questions

 What is a shell?
 How is shell programming better than using gcc compiler?
 What is shell scripting?
 Give the command to display CPU information.
 Give the command to mount the file system.
 What environmental variable is used to display the home folder?
 What environmental variable is used to display the path?
 What environmental variable is used to display the shell being used?
 What command is used to display the present working directory?
 What is the command uname used for?

ACTIVITY FOR THE STUDENTS

Write a Script to display the statistics of the current logged in user.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 168
Introduction to Linux (CSP3213)
Program 35

Aim: Write script called say Hello, put this script into your startup file called .bash_profile,
the script should run as soon as you logon to system, and it print any one of the following
message in info box using dialog utility, if installed in your system, If dialog utility is not
installed then use echo statement to print message : -

Good Morning
Good Afternoon
Good Evening , according to system time.

Answer: #!/bin/bash

temph=`date | cut -c12-13`


dat=`date +"%A %d in %B of %Y (%r)"`

if [ $temph -lt 12 ]
then
mess="Good Morning $LOGNAME, Have nice day!"
fi

if [ $temph -gt 12 -a $temph -le 16 ]


then
mess="Good Afternoon $LOGNAME"
fi

if [ $temph -gt 16 -a $temph -le 18 ]


then
mess="Good Evening $LOGNAME"
fi

if which dialog > /dev/null


then
dialog --backtitle "Linux Shell Script Tutorial"\
--title "(-: Welcome to Linux :-)"\
--infobox "\n$mess\nThis is $dat" 6 60
echo -n " Press a key to continue. . . "
read
clear
else
echo -e "$mess\nThis is $dat"
fi

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 169
Introduction to Linux (CSP3213)

Learning Outcome:
Process scheduling through command line.

Viva Questions

 Why do you need process scheduling?


 What is at command used for?
 Give the syntax for at command?
 How is at command different from batch command?
 What server processes get initialized during system start up and then wait for a user
or system request indicating that their service is required?
 Give an example of processes that are scheduled to run but are then disconnected
form the terminal.
 Give all the possible states of processes.
 What do you mean by niceness?
 What is the unique identifier of a process?
 What is the symbol for a low priority process?
 What is the symbol for a high priority process?
 Where is the crontab file located?

ACTIVITY FOR THE STUDENTS

Schedule birthdays of your 2 friends. Display HAPPY BIRTHDAY and the name of the friend
on the particular date.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 170
Introduction to Linux (CSP3213)
Program 36

Aim: Configuration, Printing Operations.

PRINTING

lpr Sends a job to the printer.


Usage: lpr- P <printer-name><file-name>
Options: -n specifies the number of copies.

Eg: lpr -P triglyph -3 myfile


prints 3 copies of myfile on trilyph

lpq: Displays the printer queue including the job number.


Usage: lpq -P <printer-name>

Lprm: Removes a job from the printer queue.


Usage: lprm -P <printer-name><job-number>

Print: Sends the job to the printer.


Usage: print -P <printer-name><file-name>

Learning Outcome:

Printing operations through shell commands are learned.

Viva Questions:

 What is the command for removing a job from the printer queue?
 What will the command and syntax if you need to print 5 copies of the same
document?
 Display all the active jobs on the printer?
 What is the purpose of lpr command?
 What is the purpose of lpr –P command?
 What is the purpose of lprm command?
 What is the purpose of lpq command?
 Send the job to the printer
 Remove a job from the printer.
 Display the jobs in the printer queue.

ACTIVITY FOR THE STUDENTS

Perform the lab exercises at the end of your MOOC course.

Chandigarh - Patiala National Highway(NH-64),


Tehsil: Rajpura , Distt. : Patiala - 140401.
P a g e | 171