Sunteți pe pagina 1din 55

Gurpreet Gill Univ. Roll.no.

- 517031789

PRACTICAL NO. 1 :- INSTALLATION OF LINUX


Steps to Get You Started

Do You Have the Right Components?

If you have purchased the Official Red Hat Linux boxed set, you are ready to go. However,
mistakes occasionally happen, so now is a good time to double-check the contents of your
product.

A black, red, and white Registration Information card is included with your product. A list of
the contents of your boxed set version is on the back of the card. Please read over the list and
check to make sure that you have all the CDs and manuals that are included with the version
of Red Hat Linux that you purchased.

If you have purchased the Official Red Hat Linux boxed set from Red Hat, Inc. (or one of our
distributors), and you are missing one or more of the items listed, please let us know. Contact
information is also available on the Registration Information card.

Is Your Hardware Compatible?

Hardware compatibility is particularly important if you have an older system or a system that
you built yourself. Red Hat Linux 8.0 should be compatible with most hardware in systems
that were factory built within the last two years. However, hardware specifications change
almost daily, so it is hard to guarantee that your hardware will be 100% compatible.

Do You Have Enough Disk Space?

Nearly every modern-day operating system (OS) uses disk partitions, and Red Hat Linux is
no exception. When you install Red Hat Linux, you may have to work with disk partitions

If Red Hat Linux will share your system with another OS, you will need to make sure you
have enough available disk space on your hard drive(s) for this installation

The disk space used by Red Hat Linux must be separate from the disk space used by other
OSes you may have installed on your system, such as Windows, OS/2, or even a different
version of Linux. At least two partitions (/ and swap) must be dedicated to Red Hat Linux.

Before you start the installation process, one of the following conditions must be met:

• Your computer must have enough unpartitioned disk space for the installation of Red
Hat Linux.
• You must have one or more partitions that may be deleted, thereby freeing up enough
disk space to install Red Hat Linux.

INSTALLATION DISK SPACE REQUIREMENTS


INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 1
Gurpreet Gill Univ. Roll.no.- 517031789

Personal Desktop

A personal desktop installation, including a graphical desktop environment, requires at


least 1.5 GB of free space. Choosing both the GNOME and KDE desktop
environments requires at least 1.8 GB of free disk space.

Workstation

A workstation installation, including a graphical desktop environment and software


development tools, requires at least 2.0 GB of free space. Choosing both the GNOME
and KDE desktop environments requires at least 2.3 GB of free disk space.

Server

A server installation requires 1.3 GB for a minimal installation without X (the


graphical environment), at least 1.4 GB of free space if all package groups other than
X are installed, and at least 2.1 GB to install all packages including the GNOME and
KDE desktop environments.

Custom

A Custom installation requires 400 MB for a minimal installation and at least 4.5 GB
of free space if every package is selected.

Can You Install Using the CD-ROM?

There are several methods that can be used to install Red Hat Linux.

Installing from a CD-ROM requires that you have purchased a Red Hat Linux 8.0 boxed set,
or you have a Red Hat Linux CD-ROM, and you have a CD-ROM drive. Most new
computers will allow booting from the CD-ROM. If your system will support booting from
the CD-ROM, it is an easy way to begin a local CD-ROM installation.

Installing Red Hat Linux

The following topics are discussed:

• Becoming familiar with the installation program's user interface


• Starting the installation program
• Selecting an installation method
• Configuration steps during the installation (language, keyboard, mouse, etc.)

Booting the Installation Program


You can boot the Red Hat Linux installation program using any one of the following media
(depending upon what your system can support):

• Bootable CD-ROM — Your machine supports a bootable CD-ROM drive and you
want to perform a local CD-ROM installation.

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 2


Gurpreet Gill Univ. Roll.no.- 517031789

• Local boot diskette — Your machine will not support a bootable CD-ROM and you
want to install from a local CD-ROM or a hard drive.
• Network boot diskette — Use a network boot diskette to install via NFS, FTP, and
HTTP.
• PCMCIA boot diskettes — Use PCMCIA boot diskettes when you need PCMCIA
support, but your machine does not support booting from the CD-ROM drive or if you
need PCMCIA support in order to make use of the CD-ROM drive on your system.
The PCMCIA boot diskettes can be used for all installation methods (CD-ROM, hard
drive, NFS, FTP, and HTTP).

Insert the boot diskette into your computer's first diskette drive and reboot (or boot using the
CD-ROM, if your computer supports booting from it). Your BIOS settings may need to be
changed to allow you to boot from the diskette or CD-ROM.

After a short delay, a screen containing the boot: prompt should appear. The screen contains
information on a variety of boot options. Each boot option also has one or more help screens
associated with it. To access a help screen, press the appropriate function key as listed in the
line at the bottom of the screen.

As you boot the installation program, be aware of two issues:

• Once you see the boot: prompt, the installation program will automatically begin if
you take no action within the first minute. To disable this feature, press one of the help
screen function keys.
• If you press a help screen function key, there will be a slight delay while the help
screen is read from the boot media.

Normally, you only need to press [Enter] to boot. Watch the boot messages to see if the Linux
kernel detects your hardware. If your hardware is properly detected, please continue to the
next section. If it does not properly detect your hardware, you may need to restart the
installation in expert mode.

Booting Without Diskettes

The Red Hat Linux CD-ROM can be booted by computers that support bootable CD-ROMs.
Not all computers support this feature, so if your system cannot boot from the CD-ROM,
there is one other way to start the installation without using a boot diskette. The following
method is specific to x86-based computers only.

If you have MS-DOS installed on your system, you can boot directly from the CD-ROM drive
without using a boot diskette. To do this (assuming your CD-ROM is drive d:), use the
following commands:

C:\> d:
D:\> cd \dosutils
D:\dosutils> autoboot.bat

This method will not work if run in a DOS window — the autoboot.bat file must be
executed with DOS as the only operating system. In other words, Windows cannot be
running. If your computer cannot boot directly from CD-ROM (and you cannot use a DOS-
based autoboot.bat), you will have to use a boot diskette to start the installation.
INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 3
Gurpreet Gill Univ. Roll.no.- 517031789

Selecting an Installation Method


What type of installation method do you wish to use? The following installation methods are
available:

CD-ROM

If you have a CD-ROM drive and the Red Hat Linux CD-ROMs, you can use this
method. You will need a boot diskette or a bootable CD-ROM. PCMCIA boot and
driver diskettes may also be used.

Hard Drive

If you have copied the Red Hat Linux ISO images to a local hard drive, you can use
this method. You will need a boot diskette. PCMCIA boot and driver diskettes may
also be used.

NFS Image

If you are installing from an NFS server using ISO images or a mirror image of Red
Hat Linux, you can use this method. You will need a network boot diskette. PCMCIA
boot and driver diskettes may also be used.

Installing from CD-ROM


To install Red Hat Linux from a CD-ROM, choose the CD-ROM option from the boot loader
screen and select OK. When prompted, insert the Red Hat Linux CD into your CD-ROM
drive (if you did not boot from the CD-ROM). Once the CD is in the CD-ROM drive, select
OK, and press [Enter].

Welcome to Red Hat Linux


The Welcome screen does not prompt you for any input. Please read over the help text in the
left panel for additional instructions and information on where to register your Official Red
Hat Linux product. Please notice the Hide Help button at the bottom left corner of the screen.
The help screen is open by default. If you do not want to view the help information, click on
Hide Help to minimize the help portion of the screen. Click on the Next button to continue.

Language Selection
Using your mouse, select the language you would prefer to use for the installation.Selecting
the appropriate language will also help target your time zone configuration later in the
installation. The installation program will try to define the appropriate time zone based on
what you specify on this screen.

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 4


Gurpreet Gill Univ. Roll.no.- 517031789

Language Selection

Once you select the appropriate language, click Next to continue.

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 5


Gurpreet Gill Univ. Roll.no.- 517031789

Keyboard Configuration
Using your mouse, select the correct layout type (for example, U.S. English) for the keyboard
you would prefer to use for the installation and as the system default.

Once you have made your selection, click Next to continue.

Keyboard Configuration

Mouse Configuration
Choose the correct mouse type for your system. If you cannot find an exact match, choose a
mouse type that you are sure is compatible with your system .

To determine your mouse's interface, follow the mouse cable back to where it plugs into your
system and use the following diagrams. If you are installing Red Hat Linux on a laptop
computer, in most cases the pointing device will be PS/2 compatible.

If your mouse is a serial mouse, the port will look similar to .

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 6


Gurpreet Gill Univ. Roll.no.- 517031789

If your mouse is a PS/2 mouse, the port will look similar to .

If your mouse is a USB mouse, the port will look similar to .

If your mouse is a AT (Advanced Technology) mouse, the port will look similar to .

If you cannot find a mouse that you are sure is compatible with your system, select one of the
Generic entries, based on your mouse's number of buttons, and its interface.

Mouse Configuration

If you have a PS/2, USB, or Bus mouse, you do not need to pick a port and device. If you
have a serial mouse, you should choose the correct port and device that your serial mouse is
on.

The Emulate 3 buttons checkbox allows you to use a two-button mouse as if it had three
buttons. In general, the graphical interface (the X Window System) is easier to use with a
three-button mouse. If you select this checkbox, you can emulate a third, "middle" button by
pressing both mouse buttons simultaneously.
INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 7
Gurpreet Gill Univ. Roll.no.- 517031789

Installation Type
Choose the type of installation you would like to perform . Red Hat Linux allows you to
choose the installation type that best fits your needs. Your options are Personal Desktop,
Workstation, Server, Custom, and Upgrade.

Choosing Install or Upgrade

Disk Partitioning Setup


Partitioning allows you to divide your hard drive into isolated sections, where each section
behaves as its own hard drive. Partitioning is particularly useful if you run more than one
operating system..

On this screen, you can choose to perform automatic partitioning, or manual partitioning
using Disk Druid or fdisk .

Automatic partitioning allows you to perform an installation without having to partition your
drive(s) yourself. If you do not feel comfortable with partitioning your system, it is
recommended that you do not choose to partition manually and instead let the installation
program partition for you.

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 8


Gurpreet Gill Univ. Roll.no.- 517031789

To partition manually, choose either the Disk Druid or fdisk (recommended for experts only)
partitioning tool.

Disk Partitioning Setup

Automatic Partitioning
Automatic partitioning allows you to have some control concerning what data is removed (if
any) from your system. Your options are:

• Remove all Linux partitions on this system — select this option to remove only
Linux partitions (partitions created from a previous Linux installation). This will not
remove other partitions you may have on your hard drive(s) (such as VFAT or FAT32
partitions).
• Remove all partitions on this system — select this option to remove all partitions on
your hard drive(s) (this includes partitions created by other operating systems such as
Windows 95/98/NT/2000 or NTFS partitions).
• Keep all partitions and use existing free space — select this option to retain your
current data and partitions, assuming you have enough free space available on your
hard drive(s).

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 9


Gurpreet Gill Univ. Roll.no.- 517031789

Automatic Partitioning

Using your mouse, choose the hard drive(s) on which you want Red Hat Linux to be installed.
If you have two or more hard drives, you can choose which hard drive(s) should contain this
installation. Unselected hard drives, and any data on them, will not be touched.

To review and make any necessary changes to the partitions created by automatic partitioning,
select the Review option. After selecting Review and clicking Next to move forward, you
will see the partitions created for you in Disk Druid. You will also be able to make
modifications to these partitions if they do not meet your needs.

Click Next once you have made your selections to proceed.

Partitioning Your System


If you chose automatic partitioning and selected Review, you can either accept the current
partition settings (click Next), or modify the setup using Disk Druid, the manual partitioning
tool.

At this point, you must tell the installation program where to install Red Hat Linux. This is
done by defining mount points for one or more disk partitions in which Red Hat Linux will be
installed. You may also need to create and/or delete partitions at this time.

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 10


Gurpreet Gill Univ. Roll.no.- 517031789

Partitioning with Disk Druid

The partitioning tool used by the installation program is Disk Druid. With the exception of
certain esoteric situations, Disk Druid can handle the partitioning requirements for a typical
installation.

Adding Partitions
To add a new partition, select the New button. A dialog box appears .

Creating a New Partition

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 11


Gurpreet Gill Univ. Roll.no.- 517031789

• Mount Point: Enter the partition's mount point. For example, if this partition should
be the root partition, enter /; enter /boot for the /boot partition, and so on. You can
also use the pull-down menu to choose the correct mount point for your partition.
• File System Type: Using the pull-down menu, select the appropriate file system type
for this partition.
• Allowable Drives: This field contains a list of the hard disks installed on your system.
If a hard disk's box is highlighted, then a desired partition can be created on that hard
disk. If the box is not checked, then the partition will never be created on that hard
disk. By using different checkbox settings, you can have Disk Druid place partitions
as you see fit, or let Disk Druid decide where partitions should go.
• Size (Megs): Enter the size (in megabytes) of the partition. Note, this field starts with
100 MB; unless changed, only a 100 MB partition will be created.
• Additional Size Options: Choose whether to keep this partition at a fixed size, to
allow it to "grow" (fill up the available hard drive space) to a certain point, or to allow
it to grow to fill any remaining hard drive space available.

If you choose Fill all space up to (MB), you must give size constraints in the field to
the right of this option. This allows you to keep a certain amount of space free on your
hard drive for future use.

• Force to be a primary partition: Select whether the partition you are creating should
be one of the first four partitions on the hard drive. If unselected, the partition created
will be a logical partition.
• Check for bad blocks: Checking for bad blocks can help prevent data loss by locating
the bad blocks on a drive and making a list of them to prevent using them in the
future. If you wish to check for bad blocks while formatting each file system, please
make sure to select this option.

Selecting Check for bad blocks may dramatically increase your total installation
time. Since most newer hard drives are quite large in size, checking for bad blocks
may take a long time; the length of time depends on the size of your hard drive. If you
choose to check for bad blocks, you can monitor your progress on virtual console #6.

• Ok: Select Ok once you are satisfied with the settings and wish to create the partition.
• Cancel: Select Cancel if you do not want to create the partition.

Editing Partitions
To edit a partition, select the Edit button or double-click on the existing partition.

Deleting a Partition
To delete a partition, highlight it in the Partitions section and click the Delete button. You
will be asked to confirm the deletion.

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 12


Gurpreet Gill Univ. Roll.no.- 517031789

Boot Loader Configuration


In order to boot the system without a boot diskette, you usually need to install a boot loader.
A boot loader is the first software program that runs when a computer starts. It is responsible
for loading and transferring control to the operating system kernel software. The kernel, in
turn, initializes the rest of the operating system.

The installation program provides two boot loaders for you to choose from, GRUB and LILO.

GRUB (GRand Unified Bootloader), which is installed by default, is a very powerful boot
loader. GRUB can load a variety of free operating systems, as well as proprietary operating
systems with chain-loading (the mechanism for loading unsupported operating systems by
loading another boot loader, such as DOS or Windows).

LILO (LInux LOader) is a versatile boot loader for Linux. It does not depend on a specific file
system, can boot Linux kernel images from floppy diskettes and hard disks, and can even boot
other operating systems.

Boot Loader Configuration

If you do not want to install GRUB as your boot loader, click Change boot loader. You can
then choose to install LILO or choose not to install a boot loader at all.

If you already have a boot loader that can boot Linux and do not want to overwrite your
current boot loader, or if you plan to boot the system using boot diskettes, choose Do not
install a boot loader by clicking on the Change boot loader button.

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 13


Gurpreet Gill Univ. Roll.no.- 517031789

Every bootable partition is listed, including partitions used by other operating systems. The
partition holding your the system's root file system will have a Label of Red Hat Linux (for
GRUB) or linux (for LILO). Other partitions may also have boot labels. If you would like to
add or change the boot label for other partitions that have been detected by the installation
program, click once on the partition to select it. Once selected, you can change the boot label
by clicking the Edit button.

Network Configuration
If you do not have a network device, you will not see this screen.

If you have a network device and you have not already configured your networking (such as
booting from a network boot disk you created and entering in your network information as
prompted), you now have the opportunity to do so.

Network Configuration

The installation program will automatically detect any network devices you have and display
them in the Network Devices list.

Once you have selected a network device, click Edit. From the Edit Interface pop-up screen,
you can choose to configure the IP address and Netmask of the device via DHCP (or
manually if DHCP is not selected) and you can choose to activate the device at boot time. If
you select Activate on boot, your network interface will be started when you boot. If you do
not have DHCP client access or you are unsure what to provide here, please contact your
network administrator.

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 14


Gurpreet Gill Univ. Roll.no.- 517031789

Editing a Network Device

If you have a hostname (fully qualified domain name) for the network device, you can choose
to have DHCP (Dynamic Host Configuration Protocol) automatically detect it or you can
manually enter the hostname in the field provided.

Finally, if you entered the IP and Netmask information manually, you may also enter the
Gateway address and the Primary, Secondary, and Tertiary DNS addresses.

Firewall Configuration
Red Hat Linux offers firewall protection for enhanced system security. A firewall exists
between your computer and the network, and determines which resources on your computer
remote users on the network can access. A properly configured firewall can greatly increase
the security of your system.

Firewall Configuration

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 15


Gurpreet Gill Univ. Roll.no.- 517031789

Language Support Selection


Red Hat Linux can install and support multiple languages for use on your system.

You must select a language to use as the default language. The default language will be used
on the system once the installation is complete. If you choose to install other languages during
this installation, you can change your default language after the installation.

If you are only going to use one language on your system, selecting only that language will
save significant disk space. The default language is the language you selected to use during
the installation.

Language Support Selection

To use more than one language on your system, choose specific languages to be installed or
select all languages to have all available languages installed on your Red Hat Linux system.

Time Zone Configuration


You can set your time zone by selecting your computer's physical location or by specifying
your time zone's offset from Universal Time, Coordinated (UTC).

Notice the two tabs at the top of the screen. The first tab allows you to configure your time
zone by your location.

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 16


Gurpreet Gill Univ. Roll.no.- 517031789

On the interactive map, you can also click on a specific city, which is marked by a yellow dot;
a red X will appear indicating your selection. You can also scroll through a list and choose a
time zone.

The second tab allows you to specify a UTC offset. The tab displays a list of offsets to choose
from, as well as an option to set daylight saving time.

Configuring the Time Zone

On both tabs, you can select System Clock uses UTC. Please select this if you know that
your system is set to UTC.

Account Configuration
The Account Configuration screen allows you to set your root password. Additionally, you
can set up user accounts for you to log in to once the installation is complete.

Account Creation

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 17


Gurpreet Gill Univ. Roll.no.- 517031789

Setting the Root Password


Setting up a root account and password is one of the most important steps during your
installation. Your root account is similar to the administrator account used on Windows NT
machines. The root account is used to install packages, upgrade RPMs, and perform most
system maintenance. Logging in as root gives you complete control over your system.

The root password must be at least six characters long; the password you type is not echoed to
the screen. You must enter the password twice; if the two passwords do not match, the
installation program will ask you to enter them again.

You should make the root password something you can remember, but not something that is
easy for someone else to guess. Your name, your phone number, qwerty, password, root,
123456, and anteater are all examples of bad passwords. Good passwords mix numerals with
upper and lower case letters and do not contain dictionary words: Aard387vark or
420BMttNT, for example. Remember that the password is case-sensitive. If you write down
your password, keep it in a secure place. However, it is recommended that you do not write
down this or any password you create.

Setting Up User Accounts


If you choose to create a user account now, you will have an account to log in to once the
installation has completed. This allows you to safely and easily log into your computer
without having to be root to create your user account.

Creating a User Account

Click the Add button to add a new, non-root, user. Enter a user name for the user account.
Next, enter and confirm a password for that user account. Enter the full name of the account
user and click OK. Your account information will be added to the account list.

You can also Edit or Delete the user accounts you have created and no longer want.

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 18


Gurpreet Gill Univ. Roll.no.- 517031789

Package Group Selection


After your partitions have been selected and configured for formatting, you are ready to select
packages for installation.

You can select package groups, which group components together according to function (for
example, X Window System, Editors), individual packages, or a combination of the two.

To select a component, click on the checkbox beside it.

Package Group Selection

Select each component you wish to install. Selecting Everything (at the end of the
component list) during a custom installation installs all packages included with Red Hat
Linux.Once a package group has been selected, click on Details to view which packages will
be installed by default and to add or remove optional packages from that group.

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 19


Gurpreet Gill Univ. Roll.no.- 517031789

To select packages individually, check the Select Individual Packages box at the bottom of
the screen.

Selecting Individual Packages


After selecting the components you wish to install, you can select or deselect individual
packages using your mouse You can choose to view the individual packages in Tree View or
Flat View.

Tree View allows you to see the packages grouped by application type.

Flat View allows you to see all of the packages in an alphabetical listing on the right of the
screen.

Selecting Individual Packages

Using Tree View, you see a listing of package groups. When you expand this list (by double-
clicking on the folder arrow beside a package group name) and pick one group, the list of
packages in that group appears in the panel on the right. Flat View allows you to see all of the
packages in an alphabetical listing on the right of the screen.

To sort packages alphabetically, click on the Package tab. To sort packages by size, click on
the Size (MB) tab.

To select an individual package, double-click the checkbox beside the package name. A check
mark in the box means that a package has been selected.

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 20


Gurpreet Gill Univ. Roll.no.- 517031789

For more information about a specific package, click on the individual package name. The
package information will appear at the bottom of the screen.

You can also select or deselect all packages listed within a particular group, by clicking on the
Select all in group or Unselect all in group buttons.

Preparing to Install
You should now see a screen preparing you for the installation of Red Hat Linux.

For your reference, a complete log of your installation can be found in /root/install.log
once you reboot your system.

Installing Packages
At this point there is nothing left for you to do until all the packages have been installed.How
quickly this happens depends on the number of packages you have selected and your
computer's speed.

Installing Packages

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 21


Gurpreet Gill Univ. Roll.no.- 517031789

Boot Disk Creation


To create a boot disk, insert a blank, formatted diskette into your diskette drive .It is highly
recommended that you create a boot disk. If, for some reason, your system were not able to
boot properly using GRUB, LILO, or a third-party boot loader, a boot disk would enable you
to properly boot your Red Hat Linux system.

After a short delay, your boot disk will be created; remove it from your diskette drive and
label it clearly. Note that if you would like to create a boot disk after the installation, you will
be able to do so. For more information, please see the mkbootdisk man page, by typing man
mkbootdisk at the shell prompt.

If you do not want to create a boot disk, make sure to select the appropriate option before you
click Next.

If you boot your system with the boot disk (instead of GRUB or LILO) , make sure you create
a new boot disk whenever you make any changes to your kernel (including the installation of
a new kernel).

Creating Your Boot Disk

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 22


Gurpreet Gill Univ. Roll.no.- 517031789

PRACTICAL NO. 2 :- EXPLAIN VARIOUS UNIX AND LINUX


COMMANDS
access()
Used to check the accessibility of files

int
Access(pathname, access_mode)
Char* pathname;
int access-mode;
The access modes are.
04 read
02 write
01 execute (search)
00 checks existence of a file

& operator
execute a command as a background process.

banner
prints the specified string in large letters. Each argument may be upto 10 characters long.

break
is used to break out of a loop. It does not exit from the program.

Cal
Produces a calender of the current month as standard output. The month (1-12) and year (1-
9999) must be specified in full numeric format.

Cal [[ month] year]

Calendar
Displays contents of the calendar file

case operator
The case operator is used to validate multiple conditions.

Case $string in

Pattern 1)
Command list;;
Command list;;

Pattern 3)
Command list;;
easc

cat
(for concatenate) command is used to display the contents of a file. Used without arguments it
takes input from standard input <Dtrl d> is used to terminate input.
INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 23
Gurpreet Gill Univ. Roll.no.- 517031789

cat [filename(s)]
cat > [filename]
Data can be appended to a file using >>

Some of the available options are :


Cat [-options] filename(S)
-s silent about files that
cannot be accessed
-v enables display of non printinging characters (except tabs, new lines, form-

feeds)
-t when used with –v, it causes tabs to be printed as ^I’s
-e when used with –v, it causes $ to be printed at the end of each line
The –t and –e options are ignored if the –v options is not specified.

cd
Used to change directories

chgrp
Changes the group that owns a file.
Chgrp [grou –id] [filename]

chmod
Allows file permissions to be changed for each user. File permissions can be changed only by
the owner (s).
Chmod [+/-][rwx] [ugo] [filename]

chown
Used to change the owner of a file.
The command takes a file(s) as source files and the login id of another user as the target.
Chown [user-id] [filename]

cmp
The cmp command compares two files (text or binary) byte-by-byte and displays the first
occurrence where the files differ.
Cmp [filename1] [filename2] -1 gives a long listing

comm.
The comm command compares two sorted files and displays the instances that are common.
The display is separated into 3 columns.
Comm. filename1 filename2
first displays what occurs in first files but not in the second
second displays what occurs in second file but not in first
third displays what is common in both files

continue statement
The rest of the commands in the loop are ignored. It moves out of the loop and moves on the
next cycle.

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 24


Gurpreet Gill Univ. Roll.no.- 517031789

cp
The cp (copy) command is used to copy a file.
Cp [filename1] [filename2]

cpio(copy input/output)
Utility program used to take backups.
Cpio operates in three modes:
-o output
-i input
-p pass

creat()
the system call creates a new file or prepares to rewrite an existing file. The file pointer is set
to the beginning of file.
#include<sys/tyes.h>
#include<sys/stat.h>
int creat(path, mode)

char *path;
int mode;

cut
used to cut out parts of a file. It takes filenames as command line arguments or input from
standard input. The command can cut columns as well as fields in a file. It however does not
delete the selected parts of the file.
Cut [-ef] [column/fie,d] filename
Cut-d “:” –f1,2,3 filename
Where –d indicates a delimiter specified within “:”

df
used to find the number of free blocks available for all the mounted file systems.
#/etc/df [filesystem]

diff
the diff command compares text files. It gives an index of all the lines that differ in the two
files along with the line numbers. It also displays what needs to be changed.
Diff filename1 filename2

echo
The echo command echoes arguments on the command line.
echo [arguments]

env
Displays the permanent environment variables associated with a user’s login id

exit command
Used to stop the execution of a shell script.

expr command
Expr (command) command is used for numeric computation.

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 25


Gurpreet Gill Univ. Roll.no.- 517031789

The operators + (add), -(subtract), *(multiplu), /(divide), (remainder) are allowed. Calculation
are performed in order of normal numeric precedence.

find
The find command searches through directories for files that match the specified criteria. It
can take full pathnames and relative pathnames on the command line.
To display the output on screen the –print option must be specified

for operator
The for operator may be used in looping constructs where there is repetitive execution of a
section of the shell program.
For var in vall val2 val3 val4;

Do commnds; done

fsck
Used to check the file system and repair damaged files. The command takes a device name as
an argument
# /etc/fsck /dev/file-system-to-be-checked.

grave operator
Used to store the standard the output of a command in an enviroment variable. (‘)

grep
The grep (global regular expression and print) command can be used as a filter to search for
strings in files. The pattern may be either a fixed character string or a regular expression.
Grep “string” filename(s)

HOME
User’s home directory

if operator
The if operator allows conditional operator

If expression; then commands; fi


if … then…else… fi
$ if; then

commands
efile; then

commands
fi

kill
used to stop background processes

In
used to link files. A duplicate of a file is created with another name

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 26


Gurpreet Gill Univ. Roll.no.- 517031789

LOGNAME
displays user’s login name

ls
Lists the files in the current directory

Some of the available options are:


-l gives a long listing
-a displays all file{including hidden files

lp
used to print data on the line printer.
Lp [options] filename(s)

mesg
The mesg command controls messages received on a terminal.
-n does not allow messages to be displayed on screen
-y allows messages to be displayed on screen

mkdir
used to create directories

more
The more command is used to dispay data one screenful at a time.
More [filename]

mv
Mv (move) moves a file from one directory to another or simply changes filenames. The
command takes filename and pathnames as source names and a filename or exiting directory
as target names.
mv [source-file] [target-file]

news
The news command allows a user to read news items published by the system administrator.

ni
Displays the contents of a file with line numbers

passwd
Changes the password

paste
The paste command joins lines from two files and displays the output. It can take a number of
filenames as command line arguments.
paste file1 file2

PATH
The directories that the system searches to find commands

pg
Used to display data one page (screenful) at a time. The command can take a number of
INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 27
Gurpreet Gill Univ. Roll.no.- 517031789

filenames as arguments.
Pg [option] [filename] [filename2]…..

pipe
Operator (1) takes the output of one commands as input of another command.

ps
Gives information about all the active processes.

PS1
The system prompt

pwd
(print working directory) displays the current directory.

rm
The rm (remove) command is used to delete files from a directory. A number of files may be
deleted simultaneously. A file(s) once deleted cannot be retrieved.
rm [filename 1] [filename 2]…

sift command
Using shift $1becomes the source string and other arguments are shifted. $2 is shifted to
$1,$3to $2 and so on.

Sleep
The sleep command is used to suspend the execution of a shell script for the specified time.
This is usually in seconds.

sort
Sort is a utility program that can be used to sort text files in numeric or alphabetical order
Sort [filename]

split
Used to split large file into smaller files
Split-n filename
Split can take a second filename on the command line.

su
Used to switch to superuser or any other user.

sync
Used to copy data in buffers to files

system0
Used to run a UNIX command from within a C program

tail
The tail command may be used to view the end of a file.
Tail [filename]

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 28


Gurpreet Gill Univ. Roll.no.- 517031789

tar
Used to save and restore files to tapes or other removable media.
Tar [function[modifier]] [filename(s)]

tee
output that is being redirected to a file can also be viewed on standard output.

test command
It compares strings and numeric values.
The test command has two forms : test command itself If test ${variable} = value then
Do commands else do commands

File
The test commands also uses special operators [ ]. These are operators following the of are
interpreted by the shell as different from wildcard characters.
Of [ -f ${variable} ]

Then
Do commands
Elif
[ -d ${variable} ]

then
do commands

else
do commands

fi
many different tests are possible for files. Comparing numbers, character strings, values of
environment variables.

time
Used to display the execution time of a program or a command. Time is reported in seconds.
Time filename values

tr
The tr command is used to translate characters.
tr [-option] [string1 [string2]]

tty
Displays the terminal pathname

umask
Used to specify default permissions while creating files.

uniq
The uniq command is used to display the uniq(ue) lines in a sorted file.
Sort filename uniq

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 29


Gurpreet Gill Univ. Roll.no.- 517031789

until
The operator executes the commands within a loop as long as the test condition is false.

wall
Used to send a message to all users logged in.
# /etc/wall message

wait
the command halts the execution of a script until all child processes, executed as background
processes, are completed.

wc
The wc command can be used to count the number of lines, words and characters in a fine.
wc [filename(s)]
The available options are:
wc –[options] [filename]
-1
-w
-c
while operator
the while operator repeatedly performs an operation until the test condition proves false.

$ while
Ø do

commands
Ø done

who
displays information about all the users currently logged onto the system. The user name,
terminal number and the date and time that each user logged onto the system.
The syntax of the who command is who [options]

write
The write command allows inter-user communication. A user can send messages by
addressing the other user’s terminal or login id.
write user-name [terminal number]

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 30


Gurpreet Gill Univ. Roll.no.- 517031789

PRACTICAL NO. 3 :- EXPALIN SHELL SCRIPTING


Shell script
A shell script is a script written for the shell, or command line interpreter, of an operating
system. It is often considered a simple domain-specific programming language. Typical
operations performed by shell scripts include file manipulation, program execution, and
printing text.

Many shell script interpreters double as command line interface, such as the various Unix
shells, Windows PowerShell or the MS-DOS COMMAND.COM. Others, such as AppleScript or
the graphical Windows Script Host (WScript.exe), add scripting capability to computing
environments without requiring a command line interface. Other examples of programming
languages primarily intended for shell scripting include DCL and JCL.

Startup Files
When a shell starts, it runs startup files to initialize itself. Which files the shell runs depends
on whether it is a login shell, an interactive shell that is not a login shell (such as you get by
giving the command bash), or a noninteractive shell (one used to execute a shell script). You
must have read access to a startup file to execute the commands in it. Typically Linux
distributions put appropriate commands in some of these files. This section covers bash
startup files.

How to write a shell script

Introduction
A shell is a command line interpretor. It takes commands and executes them. As such, it
implements a programming language. The Bourne shell is used to create shell scripts -- ie.
programs that are interpreted/executed by the shell. You can write shell scripts with the C-
shell; however, this is not covered here.

Creating a Script
Suppose you often type the command
find . -name file -print
and you'd rather type a simple command, say
sfind file
Create a shell script
% cd ~/bin
% emacs sfind
% page sfind
find . -name $1 -print
% chmod a+x sfind
% rehash
% cd /usr/local/bin
% sfind tcsh
./shells/tcsh

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 31


Gurpreet Gill Univ. Roll.no.- 517031789

Observations

This quick example is far from adequate but some observations:

1. Shell scripts are simple text files created with an editor.


2. Shell scripts are marked as executeable
3. %chmod a+x sfind
4. Should be located in your search path and ~/bin should be in your search path.
5. You likely need to rehash if you're a Csh (tcsh) user (but not again when you login).
6. Arguments are passed from the command line and referenced. For example, as $1.

#!/bin/sh
All Bourne Shell scripts should begin with the sequence
#!/bin/sh
From the man page for exec(2):

"On the first line of an interpreter script, following the "#!", is the name of a program which
should be used to interpret the contents of the file. For instance, if the first line contains "#!
/bin/sh", then the con- tents of the file are executed as a shell script."

You can get away without this, but you shouldn't. All good scripts state the interpretor
explicitly. Long ago there was just one (the Bourne Shell) but these days there are many
interpretors -- Csh, Ksh, Bash, and others.

Comments
Comments are any text beginning with the pound (#) sign. A comment can start anywhere on
a line and continue until the end of the line.

Search Path
All shell scripts should include a search path specifica- tion:
PATH=/usr/ucb:/usr/bin:/bin; export PATH
A PATH specification is recommended -- often times a script will fail for some people
because they have a different or incomplete search path.

The Bourne Shell does not export environment variables to children unless explicitly
instructed to do so by using the export command.

Argument Checking
A good shell script should verify that the arguments sup- plied (if any) are correct.
if [ $# -ne 3 ]; then
echo 1>&2 Usage: $0 19 Oct 91
exit 127
fi
This script requires three arguments and gripes accordingly.

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 32


Gurpreet Gill Univ. Roll.no.- 517031789

Exit status
All Unix utilities should return an exit status.
# is the year out of range for me?

if [ $year -lt 1901 -o $year -gt 2099 ]; then


echo 1>&2 Year \"$year\" out of range
exit 127
fi

etc...

# All done, exit ok

exit 0
A non-zero exit status indicates an error condition of some sort while a zero exit status
indicates things worked as expected.

On BSD systems there's been an attempt to categorize some of the more common exit status
codes. See /usr/include/sysexits.h.

Using exit status


Exit codes are important for those who use your code. Many constructs test on the exit status
of a command.

The conditional construct is:

if command; then
command
fi
For example,
if tty -s; then
echo Enter text end with \^D
fi
Your code should be written with the expectation that others will use it. Making sure you
return a meaningful exit status will help.

Stdin, Stdout, Stderr


Standard input, output, and error are file descriptors 0, 1, and 2. Each has a particular role and
should be used accordingly:
# is the year out of range for me?

if [ $year -lt 1901 -o $year -gt 2099 ]; then


echo 1>&2 Year \"$year\" out of my range
exit 127
fi

etc...

# ok, you have the number of days since Jan 1, ...

case `expr $days % 7` in


0)
INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 33
Gurpreet Gill Univ. Roll.no.- 517031789

echo Mon;;
1)
echo Tue;;

etc...
Error messages should appear on stderr not on stdout! Output should appear on stdout. As for
input/output dialogue:
# give the fellow a chance to quit

if tty -s ; then
echo This will remove all files in $* since ...
echo $n Ok to procede? $c; read ans
case "$ans" in
n*|N*)
echo File purge abandoned;
exit 0 ;;
esac
RM="rm -rfi"
else
RM="rm -rf"
fi
Note: this code behaves differently if there's a user to communicate with (ie. if the standard
input is a tty rather than a pipe, or file, or etc. See tty(1)).

Language Constructs
For loop iteration

Substitute values for variable and perform task:

for variable in word ...


do
command
done
For example:
for i in `cat $LOGS`
do
mv $i $i.$TODAY
cp /dev/null $i
chmod 664 $i
done
Alternatively you may see:
for variable in word ...; do command; done

• Case

Switch to statements depending on pattern match

case word in
[ pattern [ | pattern ... ] )
command ;; ] ...
esac

For example:

case "$year" in
INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 34
Gurpreet Gill Univ. Roll.no.- 517031789

[0-9][0-9])
year=19${year}
years=`expr $year - 1901`
;;
[0-9][0-9][0-9][0-9])
years=`expr $year - 1901`
;;
*)
echo 1>&2 Year \"$year\" out of range ...
exit 127
;;
esac

• Conditional Execution

Test exit status of command and branch

if command
then
command
[ else
command ]
fi

For example:

if [ $# -ne 3 ]; then
echo 1>&2 Usage: $0 19 Oct 91
exit 127
fi

Alternatively you may see:

if command; then command; [ else command; ] fi

• While/Until Iteration

Repeat task while command returns good exit status.

{while | until} command


do
command
done

For example:

# for each argument mentioned, purge that directory

while [ $# -ge 1 ]; do
_purge $1
shift
done

Alternatively you may see:

while command; do command; done


INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 35
Gurpreet Gill Univ. Roll.no.- 517031789

• Variables

Variables are sequences of letters, digits, or underscores beginning with a letter or


underscore. To get the contents of a variable you must prepend the name with a $.

Numeric variables (eg. like $1, etc.) are positional vari- ables for argument
communication.

o Variable Assignment

Assign a value to a variable by variable=value. For example:

PATH=/usr/ucb:/usr/bin:/bin; export PATH

or

TODAY=`(set \`date\`; echo $1)`

o Exporting Variables

Variables are not exported to children unless explicitly marked.

# We MUST have a DISPLAY environment variable

if [ "$DISPLAY" = "" ]; then


if tty -s ; then
echo "DISPLAY (`hostname`:0.0)? \c";
read DISPLAY
fi
if [ "$DISPLAY" = "" ]; then
DISPLAY=`hostname`:0.0
fi
export DISPLAY
fi

Likewise, for variables like the PRINTER which you want hon- ored by lpr(1).
From a user's .profile:

PRINTER=PostScript; export PRINTER

Note: that the Cshell exports all environment variables.

o Referencing Variables

Use $variable (or, if necessary, ${variable}) to reference the value.

# Most user's have a /bin of their own

if [ "$USER" != "root" ]; then


PATH=$HOME/bin:$PATH
else
PATH=/etc:/usr/etc:$PATH
fi

The braces are required for concatenation constructs.


INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 36
Gurpreet Gill Univ. Roll.no.- 517031789

$p_01

The value of the variable "p_01".

${p}_01

The value of the variable "p" with "_01" pasted onto the end.

o Conditional Reference
o ${variable-word}

If the variable has been set, use it's value, else use word.

POSTSCRIPT=${POSTSCRIPT-PostScript};
export POSTSCRIPT

${variable:-word}

If the variable has been set and is not null, use it's value, else use word.

These are useful constructions for honoring the user envi- ronment. Ie. the user
of the script can override variable assignments. Cf. programs like lpr(1) honor
the PRINTER environment variable, you can do the same trick with your shell
scripts.

${variable:?word}

If variable is set use it's value, else print out word and exit. Useful for bailing
out.

o Arguments

Command line arguments to shell scripts are positional vari- ables:

$0, $1, ...

The command and arguments. With $0 the command and the rest the
arguments.

$#

The number of arguments.

$*, $@

All the arguments as a blank separated string. Watch out for "$*" vs. "$@".
And, some commands:

shift

Shift the postional variables down one and decrement number of arguments.

set arg arg ...


INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 37
Gurpreet Gill Univ. Roll.no.- 517031789

Set the positional variables to the argument list.

Command line parsing uses shift:

# parse argument list

while [ $# -ge 1 ]; do
case $1 in
process arguments...
esac
shift
done

A use of the set command:

# figure out what day it is

TODAY=`(set \`date\`; echo $1)`

cd $SPOOL

for i in `cat $LOGS`


do
mv $i $i.$TODAY
cp /dev/null $i
chmod 664 $i
done

o Special Variables
o $$

Current process id. This is very useful for constructing temporary files.

tmp=/tmp/cal0$$
trap "rm -f $tmp /tmp/cal1$$ /tmp/cal2$$"
trap exit 1 2 13 15
/usr/lib/calprog >$tmp

$?

The exit status of the last command.

$command
# Run target file if no errors and ...

if [ $? -eq 0 ]
then
etc...
fi

• Quotes/Special Characters

Special characters to terminate words:

; & ( ) | ^ < > new-line space tab

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 38


Gurpreet Gill Univ. Roll.no.- 517031789

These are for command sequences, background jobs, etc. To quote any of these use a
backslash (\) or bracket with quote marks ("" or '').

Single Quotes

Within single quotes all characters are quoted -- including the backslash. The result is
one word.

grep :${gid}: /etc/group | awk -F: '{print $1}'

Double Quotes

Within double quotes you have variable subsitution (ie. the dollar sign is interpreted)
but no file name generation (ie. * and ? are quoted). The result is one word.

if [ ! "${parent}" ]; then
parent=${people}/${group}/${user}
fi

Back Quotes

Back quotes mean run the command and substitute the output.

if [ "`echo -n`" = "-n" ]; then


n=""
c="\c"
else
n="-n"
c=""
fi

and

TODAY=`(set \`date\`; echo $1)`

• Functions

Functions are a powerful feature that aren't used often enough. Syntax is

name ()
{
commands
}

For example:

# Purge a directory

_purge()
{
# there had better be a directory

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 39


Gurpreet Gill Univ. Roll.no.- 517031789

if [ ! -d $1 ]; then
echo $1: No such directory 1>&2
return
fi

etc...
}

Within a function the positional parmeters $0, $1, etc. are the arguments to the
function (not the arguments to the script).

Within a function use return instead of exit.

Functions are good for encapsulations. You can pipe, redi- rect input, etc. to functions.
For example:

# deal with a file, add people one at a time

do_file()
{
while parse_one

etc...
}

etc...

# take standard input (or a specified file) and do it.

if [ "$1" != "" ]; then


cat $1 | do_file
else
do_file
fi

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 40


Gurpreet Gill Univ. Roll.no.- 517031789

PRACTICAL NO. 4 :- EXPALIN VARIOUS SHELL


COMMANDS WITH SYNTAX

What is a shell ?

-The shell is the command line


interface.
- It is similar to the Microsoft DOS
prompt.
- It is much more powerful with its
scripting languages.
-The standard setup of Linux has
included two shells,
– bash and csh

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 41


Gurpreet Gill Univ. Roll.no.- 517031789

Figure 1:Linux
Command Line Interface

What is a shell command?


• DOS environment commands that
include major features of the
operating system
– DIR, COPY, and ATTRIB.
• These commands provide more
complicated actions.
• You could write batch files using
these commands.

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 42


Gurpreet Gill Univ. Roll.no.- 517031789

Common Shell Command:

man
• If you don’t know how to use the Linux shell
commands, you can use “man”.
– stands for MANUAL
For example,
• Usage: man <command-name>
• Example: man ls
– press q when you finish reading the manual of
the command

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 43


Gurpreet Gill Univ. Roll.no.- 517031789

pwd
• The pwd command,
– stands for Present Working Directory
• By typing the command and hitting
“Enter”, you will be informed of which
directory you are currently in.
• Usage: pwd

cd
• The cd command allows you to change your
current directory to any accessible
directory on the system.
• Usage: cd <directory>
• Example: cd /usr/X11R6/bin
Note:
cd without any parameter will bring you
back to your home directory.

ls
• The ls command can be used to view the
contents of the current directory.
• Usage: ls [option] <filename>
• Example: ls –al /

Find, Grep and Cat


• The find and grep commands are for searching
files.
– find is used to search for files by a number of
criteria, including name or date of creation.
– grep is used to search the contents of files.
• The cat command combines one or more files
and displays them on the standard output.
– If no files are given, the standard input is written
to the standard output.
For example,
• Usage of find command:
– find <starting-directory> <parameters> <actions>
• Usage of grep command:
– grep <text-pattern> <file-list>
• Usage of cat command:
– cat <options> <filenam
According to the File System Standard
(FSSTND) proposed in 1994, every LINUX
INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 44
Gurpreet Gill Univ. Roll.no.- 517031789

system should contain a set of standard


files and directories
root /
bin
boot dev etc home
lib lost+found mnt opt
proc
root sbin
tmp usr
var
fd hd hd

File Management

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 45


Gurpreet Gill Univ. Roll.no.- 517031789

According to the File System Standard


(FSSTND) proposed in 1994, every LINUX
system should contain a set of standard
files and directories
root /
bin
boot dev etc home
lib lost+found mnt opt
proc
root sbin
tmp usr
var
fd hd hd

group passwd
dlun guest bin lib local
File System Structure
Root Directory ( / )
– Top of the file system. Similar to C:\ in DOS
/bin
– Contain the binary (executable code) of most
essential Linux commands, e.g. bash, cat, cp, ln,
ls, etc.
/boot
– Contain all the files needed to boot the Linux
system, including the binary of the Linux kernel.
E.g., on Red Hat Linux 6.1, the kernel is in
/boot/vmlinux-2.2.5-15 file
/dev
– Contain the special files for devices, e.g. fd0,
hd0, etc.

mv, cp
• To copy files, you can use the mv or cp
commands.
For example of “mv”,
• “mv file1 file2” allows one to move file1 to
file2.
• After move, file1 will no longer exist.
– it is similar to renaming a file.

cp command is copies one file to another.


For example “cp”,
• copy file1 to file2.
INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 46
Gurpreet Gill Univ. Roll.no.- 517031789

Note that
• if file2 does not exist, it will be created;
however if it exists, it will be overwritten:
• Usage: cp file1 file2
There is NO undo command in Linux.
• The risk of doing so is smaller if you use
the -i option ("interactive") with cp.
For example,
• if file2 exists, you will be prompted before
overwriting:
• Usage: cp –i file1 file2

rm

The rm command is used for removing files.


For examples,
• To remove a file:
• Usage: rm file1
• If you use the -i option, you'll be prompted before
removing the file:
• Usage: rm -i file1
• You can also delete more files at once:
• Usage: rm file1 file2

rmdir
If the directory is empty, you can use
rmdir:
• Usage: rmdir dir1
• If you want to remove a directory with
all its contents, you can use rm with the
-r option.
– The -r option tells rm to remove a
directory Recursively:
• Usage: rm –r dir1

rm
It might be a good practice to use the -i
option when deleting a directory with its
contents
• Usage: rm -ir dir1
Notice:
Be careful with the rm command! Linux does
not have any undo commands, and it does
INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 47
Gurpreet Gill Univ. Roll.no.- 517031789

not put files into Trash where you can


recover them later. Once you have deleted a
file, it is permanently deleted from the file
system

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 48


Gurpreet Gill Univ. Roll.no.- 517031789

Program-1

Objective:
Write a programme in shell programming to find whether the input year is leap year or not.

Code:
$vi abc
echo “Enter the year :”
read yr
con1=`echo $yr \% 4|bc`
con2=`echo $yr \% 100|bc`
con3=`echo $yr \% 400|bc`
if [ $con1 –eq 0 –a $c –ne 0 –o $b –eq 0]
then
echo “Leap year.”
else
echo “Not a leap year”
fi

Output:
$ sh abc
Enter the year :
2000
Leap year

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 49


Gurpreet Gill Univ. Roll.no.- 517031789

Program-2

Objective:
Write a programme in shell programming to find the factorial of a given no.

Code:
$vi abc
echo “Enter a no. :”
read n
i=1
fact=1
while [ $i –le $n ]
do
fact= `echo $fact \* $i|bc`
i=`echo $i + 1|bc`
done
echo $fact

Output:
$ sh abc
Enter a no. :
5
120

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 50


Gurpreet Gill Univ. Roll.no.- 517031789

Program-3

Objective:
Write a programme to find the sum of five digit number.

Code:
$vi abc
echo “Enter five digit no. :”
c=0
read no
while [ $no gt 0 ]
do
b=`expr $no % 10`
no=`expr $no / 10`
c=`expr $b + $c`
done
echo “Sum of digits is ”$c

Output:
$ sh abc
Enter five digit no. :
12345
Sum of digits is 15

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 51


Gurpreet Gill Univ. Roll.no.- 517031789

Program-4

Objective:
Write a programme to enter an integer through the keyboard and find whether the given no. is
even or odd.

Code:
$vi abc
echo “Enter a given no. :”
read choice
x=`echo $choice % 2|bc`
if [ $x –eq 1 ]
then
echo “No. is odd.”
else
echo “No. is even.”
fi

Output:
$ sh abc
Enter a given no. :
12
No is even.

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 52


Gurpreet Gill Univ. Roll.no.- 517031789

PRACTICAL NO. 5 :- EXPLAIN VARIOUS UNIX


EDITORS
1.Vi Editors
This is the Original Unix Default Editor for e-mail and news articles

Vi is a modal editor; that is, when using vi, you are in an edit mode, or in a command mode.
When in the command mode, all keystrokes are interpreted as commands. When in the edit
mode, these same keystrokes are interpreted as characters to enter into the text. On mutant, vi
provides no visual clue as to which mode you are in. In order to ensure that you are in the
command mode, press the <M> key. If you are in doubt as to which mode you are in, press
the <M> key a couple of times. This will ensure that you are in the command mode, and then
you can go to the edit mode if you wish.

Vi Command Mode Commands:


Cursor Movement:

h Cursor left
j Cursor down
k Cursor up
l Cursor right
0 Cursor to beginning of line
$ Cursor to end of line
w Cursor to next word
e Cursor to end of current word
b Cursor to beginning of current word
H Cursor to top of screen
M Cursor to middle of screen
L Cursor to last line on screen

^F Scroll forward 1 screen


^D Scroll down 1/2 screen
^U Scroll up 1/2 screen
^B Scroll back 1 screen
:0 Move cursor to top of file
:$ Move cursor to last line of file

Deletion Commands

x Delete character under cursor


dw Delete word under cursor
dd Delete current line
D Delete from cursor position to end of line

Editing Commands

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 53


Gurpreet Gill Univ. Roll.no.- 517031789

a Append text after cursor


A Append at end of line
i Insert text at current cursor position
I Insert at beginning of line
r Replace character under cursor
o Open a new line above current line and enter edit mode

While editing, the backspace key works as a destructive backspace (delete). Backspacing over
characters automatically deletes them, and they must be retyped.

Exiting from Vi

The Vi write commands, listed below, always write over the file if it already existed. They do
not make any backups.

:wq Write file (save), then quit


ZZ Write file (save), then quit :x Write file (save), then quit
:q! Quit without saving

Saving your File

:w Write/save current file

Getting a new file

:n filename Read in the file called filename

Extra Commands

ncommand A number n followed by a command will repeat the command n times. For
example 9dd will delete the current line and the 8 subsequent lines.

2. Line editors
One of the interesting things about both of the standard Unix editors, ( ed and ex/vi) is that
they are "line editors" rather than page editors or document editors. This sometimes takes a
little getting used to, as most of us are more familiar with the modern, full document, or word
processors. To understand ed we need to consider the time at which ed was developed, and
technology available at the time.

Remember that ed was developed back in the late 1960’s and the "state-of-the-art" input
device back then was the teletype, typified by the ASR-33 which first saw the light of day in
1968. This absolutely classic, all-around I/O Device was able to print a blazing, (for its time),
10 characters or 80 bits per second (upper case and symbols only), generating input at the
same speed from its keyboard. It also had a built in punched paper tape reader, and could
punch paper tape for output and off-line storage. Some models of this unit could even start
and stop the paper tape reader or the paper tape punch on command from a host computer
which is why it was given the "ASR" (Automatic Send & Receive) designation in it's name.

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 54


Gurpreet Gill Univ. Roll.no.- 517031789

With a very slow I/O device long involved command names are very inefficient. That is why
most of the ed commands are only one or two characters long. In addition to being slow the
teletype or ASR 33 was a hard copy device. That meant that the user could look back on the
paper and see what they had typed, unlike a monitor where you can only see 24 lines. For that
reason there was no need to "refresh the screen" because all that would do would be print a
lot of lines, pushing the paper up at 10 characters per second which would take a lot of time.
The ed editor was designed to work on a single line of the input file at a time. Hence the
appellation ”line editor”.

As ed grew and developed over time, he acquired the ability to perform edits on a number of
lines at the same time. He has also acquired new, additional, features that made him more
powerful and more useful.

All the descendents of ed are forms of a line editor. A line editor is one which enables the
user to work with a single line of text at a time. Once ed has at least one line of text in the
working buffer, there is always a current line that is the default target for any edit.

When you open a file in ed, or when you start typing a new file, ed creates a working buffer,
called the editing buffer. This buffer holds the information in memory. Any changes you
make will not be applied to the disk file until you execute a "write to disk" command. This
means you can back out of changes easily, but it also means that you can lose a whole
session's work if you forget to write the contents of the editing buffer back to disk before you
quit ed. Fortunately, if you allow it, ed will remind you to save the contents of the editing
buffer before you exit.

X-----------X

INSTITUTE OF ENGG. & TECHNOLOGY BHADDAL 55

S-ar putea să vă placă și