Practical No. 1:-Installation of Linux: Steps To Get You Started Do You Have The Right Components?
Practical No. 1:-Installation of Linux: Steps To Get You Started Do You Have The Right Components?
Practical No. 1:-Installation of Linux: Steps To Get You Started Do You Have The Right Components?
1 :- INSTALLATION OF LINUX
Steps to Get You Started
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.
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.
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.
Workstation
Server
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.
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.
• Bootable CD-ROM — Your machine supports a bootable CD-ROM drive and you
want to perform a local CD-ROM installation.
• 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.
2
• 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.
• 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.
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.
3
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.
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.
4
Language Selection
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.
5
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.
6
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.
7
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.
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.
8
To partition manually, choose either the Disk Druid or fdisk (recommended for experts only)
partitioning tool.
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).
9
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.
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.
10
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 .
11
• 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.
12
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.
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.
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
13
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.
14
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
15
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.
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.
Notice the two tabs at the top of the screen. The first tab allows you to configure your time
zone by your location.
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.
16
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.
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
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.
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.
18
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.
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.
To select packages individually, check the Select Individual Packages box at the bottom of
the screen.
19
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.
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.
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.
20
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
21
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).
int
Access(pathname, access_mode)
Char* pathname;
22
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.
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.
cat [filename(s)]
cat > [filename]
Data can be appended to a file using >>
23
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.
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
24
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.
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
25
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
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
LOGNAME
displays user’s login name
ls
Lists the files in the current directory
lp
used to print data on the line printer.
Lp [options] filename(s)
mesg
The mesg command controls messages received on a terminal.
26
-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
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
27
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]
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
28
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
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.
29
$ 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]
30
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.
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
31
Observations
#!/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.
32
Exit status
All Unix utilities should return an exit status.
# is the year out of range for me?
etc...
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.
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.
etc...
33
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
• Case
case word in
[ pattern [ | pattern ... ] )
command ;; ] ...
esac
For example:
case "$year" in
[0-9][0-9])
34
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
if command
then
command
[ else
command ]
fi
For example:
if [ $# -ne 3 ]; then
echo 1>&2 Usage: $0 19 Oct 91
exit 127
fi
• While/Until Iteration
For example:
while [ $# -ge 1 ]; do
_purge $1
shift
done
• Variables
35
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
or
o Exporting Variables
Likewise, for variables like the PRINTER which you want hon- ored by lpr(1).
From a user's .profile:
o Referencing Variables
$p_01
36
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
The command and arguments. With $0 the command and the rest the
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.
37
Command line parsing uses shift:
while [ $# -ge 1 ]; do
case $1 in
process arguments...
esac
shift
done
cd $SPOOL
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
$?
$command
# Run target file if no errors and ...
if [ $? -eq 0 ]
then
etc...
fi
• Quotes/Special Characters
These are for command sequences, background jobs, etc. To quote any of these use a
backslash (\) or bracket with quote marks ("" or '').
38
Single Quotes
Within single quotes all characters are quoted -- including the backslash. The result is
one word.
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.
and
• 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
if [ ! -d $1 ]; then
echo $1: No such directory 1>&2
return
fi
39
etc...
}
Within a function the positional parmeters $0, $1, etc. are the arguments to the
function (not the arguments to the script).
Functions are good for encapsulations. You can pipe, redi- rect input, etc. to functions.
For example:
do_file()
{
while parse_one
etc...
}
etc...
40
PRACTICAL NO. 4 :- EXPALIN VARIOUS SHELL
COMMANDS WITH SYNTAX
What is a shell ?
41
Figure 1:Linux
Command Line Interface
42
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
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>
43
• 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 /
44
File Management
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.
rm
46
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
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
47
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
48
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
49
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
50
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.
51
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.
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
Deletion Commands
Editing Commands
52
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.
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.
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
53
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
54