Silicon Media Press Unix B01JCH3WOM
Silicon Media Press Unix B01JCH3WOM
I S B N - 8 1 - 8 7 8 7 0 - 09-5
The export rights of this book are vested solely with the publisher.
Published by Silicon Media Press, Regd. Off. I-19, Lajpat Nagar - II,
New Delhi. Works : KJ-75, Kavi Nagar, Ghaziabad. Ph - (0120)-914702867 [email protected] Typeset by : Ram Ganga Computers
(P) Ltd. and Printed by : Digisoft, D-30, Sector-6, Noida. Ph - 011891-4444598, 9810236378.
Dedicated to my parents,
Contents
UNDERSTANDING UNIX OPERATING SYSTEM ---------- 2
IMPORTANCE OF OPERATING SYSTEM ------------------ 2
FUNCTIONS OF O.S.------------------------------------------ 3
TYPES OF O.S. ------------------------------------------------ 3
INTRODUCTION TO UNIX------------------------------------ 4
HISTORY OF UNIX -------------------------------------------- 4
CHARACTERISTICS OF UNIX SYSTEM V ----------------- 6
INSIDE UNIX --------------------------------------------------- 8
Kernel .................................................................................... 9
CHARACTERISTICS OF UNIX FILE SYSTEM ----------- 11
Hierarchical Structure ......................................................... 11
Dynamic File Growth ......................................................... 11
Structure less files ............................................................... 11
Security ............................................................................... 11
Device independence .......................................................... 11
SYSTEM REQUIREMENTS --------------------------------- 11
User Login & Password ...................................................... 12
INITIAL PASSWORD ---------------------------------------- 13
SHELL GAMES ---------------------------------------------- 13
UNIX System Prompt ......................................................... 14
CHANGING PASSWORD ----------------------------------- 15
A brief session with UNIX ................................................. 16
FORMATS OF UNIX COMMANDS ------------------------ 17
Arguments to Commands ................................................... 18
Logging Out ........................................................................ 18
SHUTTING DOWN YOUR SYSTEM ----------------------- 18
SUMMARY ---------------------------------------------------- 20
EXERCISE ---------------------------------------------------- 22
THE FILE SYSTEM & GENERAL UTILITIES ------------- 24
THE UNIX FILE ............................................................... 24
Types of UNIX files ............................................................ 24
RULES FOR FILE NAMES AND DIRECTORY ----------- 27
EXERCISE ---------------------------------------------------- 80
COMMUNICATION & ELECTRONIC MAIL --------------- 82
Sending messages to other user .......................................... 82
write Command ................................................................... 82
CONTROLLING MESSAGES ------------------------------- 83
mesg Command .................................................................. 83
THE PAPER-FILLED OFFICE ------------------------------ 83
SENDING MAIL ---------------------------------------------- 84
RECEIVING MAIL ------------------------------------------- 85
THE INTERNET ---------------------------------------------- 87
CREATING MAIL --------------------------------------------- 88
HANDLING MESSAGES ------------------------------------ 90
SAVING MESSAGES ---------------------------------------- 90
SUMMARY ---------------------------------------------------- 91
EXERCISE ---------------------------------------------------- 92
TEXT EDITOR VI & TEXT PROCESSING ---------------- 94
VI EDITING MODES ---------------------------------------- 94
Calling up VI Editor ........................................................... 94
MOVING WITHIN A FILE ----------------------------------- 95
Adding text to a file [Text Input Mode] ............................. 97
CHANGING TEXT-------------------------------------------- 97
Copying & Moving Text ..................................................... 98
Restoring and Repeating Changes ...................................... 98
SAVING CHANGES TO A FILE ---------------------------- 99
Editing a Second File .......................................................... 99
Finding out File Information............................................... 99
Interrupting & Ending vi editor .......................................... 99
Accessing UNIX Commands from within vi .................... 100
Text Processing ................................................................. 100
Useful troff Commands .................................................... 101
SUMMARY -------------------------------------------------- 103
EXERCISE -------------------------------------------------- 104
MULTITASKING -------------------------------------------- 106
Multiple Command, One System...................................... 106
REAL - TIME PROCESSES ------------------------------USING THE JOB SHELL --------------------------------SWAPPING AND PAGING -------------------------------SUMMARY --------------------------------------------------
108
108
109
111
Acknowledgments
We would like to thank all of the many people who helped bring this
rectify me at many places, but also given lot of inputs about the latest
operating system - Linux.
Mini Gulati
It has been delight working with my husband and co-author Munishwar
As you read the book, you will find the answers to many of the
questions you have about UNIX.
Chapter 2 covers all about the file system of UNIX, creating, modifying
and deleting files and folders and various other associated commands.
As you move on to Chapter 3, you discover more about various UNIX
tools to play with files.
our books. We value your opinion and want to know what we are doing
right, what we could do better, what areas you would like to see us
publish in, and any other words of wisdom you are willing to pass.
Chapter 1
INTRODUCTION
UNDERSTANDING UNIX OPERATING SYSTEM
IMPORTANCE OF OPERATING SYSTEM
FUNCTIONS OF O.S.
TYPES OF O.S.
INTRODUCTION TO UNIX
HISTORY OF UNIX
CHARACTERISTICS OF UNIX SYSTEM
CHARACTERISTICS OF UNIX FILE SYSTEM
SYSTEM REQUIREMENTS
FORMATS OF UNIX COMMANDS
SHUTTING DOWN YOUR SYSTEM
Chapter 1 : Introduction
A Computer is a collection of parts, some mechanical, some electrical
and some electronics. Getting all these parts to work together is a
major problem, and that is basically what an operating system does.
It manages, the resources of a Computer System and schedules its
operation. It provides a link between the user and the computer
hardware and software.
Operating system controls nearly every aspect of the computer
system. It transfers the control of computer to user and supplies the
way of communicating with the computer. Thus it provides the
interface between user and Computer. The principal functions of
operating system include :
To deal with any faults that may occur in the computer and
inform the user/ operator.
Also, the utility programs and other application programs will not
work with just any operating system and have to be generally
matched to the operating system. Thus, the number of packages
available for your computer is heavily influenced by the popularity of
operating system that it uses.
In many ways, it doesnt matter to us if our operating system is better
or worse than some other system. What does matter is how popular
our operating system is.
Chapter 1 : Introduction
with the users. These supervisory functions are the job of the
Operating System. Basically operating system is a manager of
resources and these resources include both computer hardware and
software. Operating system in a software which is made up by set of
programs and interprets users commands to the hardware and
decreases the distance between user and machine so that user can
work in a friendly environment. So operating system is a major part
of whole system and systems efficiency depends upon operating
systems efficiency
Memory allocation
DOS
UNIX
OS/2
---------------
Every operating system has got its advantages and disadvantages. All
operating systems have more or less the same function, namely to
hold the ring between all the different hardware resources of a
computer in such a way that users can get their work done.
1)
Single Task
i)
iii)
i)
ii)
2)
ii)
3)
i)
ii)
Multi Task
Multi user
Chapter 1 : Introduction
The UNIX revolution must be one of the finest things that has
happened to the computing industry in recent times. It has a large
number of outstanding and diverse concepts, developed and perfected
over a period of time. It simplified a lot of things and yet has
phenomenal power. It has practically everything an operating system
should have, and several features which operating systems never
had. Its richness and elegance go beyond the commands and tools
that constitute it, while simplicity permeates the entire system.
UNIX is a large computer operating system environment. It has a
large set of utility programs. These utilities include general user,
programm er, type setting, communication and administrative
commands. UNIX system is useful both for developing computer
software, and for producing documents. Both of these applications,
need many and varied tools for processing files of text and numbers,
and the UNIX system comes equipped with text manipulation tools,
documentation processing utilities, an electronic mail system, and a
flexible file system to hold everything together. The UNIX system has
introduced many new features to the computer world.
Chapter 1 : Introduction
During the period of 1974 and 1979, UNIX was really a research
product, becoming popular in universities for teaching purpose. The
UNIX of 1974 was different from UNIX of 1979. During the period
many utilities and tools were added to UNIX, while the computer
industry expanded rapidly, increasing the potential market for UNIX.
UNIX also became available on microcomputers in 1980, when
Microsoft released a scaled down version of UNIX called XENIX.
Microsoft is perhaps more famous for creating an alliance with IBM
that made its DOS (Disk Operating System) the most popular
microcomputer operating system. XENIX development was taken over
by Santa Cruz Operation ( a company partially owned by Microsoft),
and SCO UNIX is now an important product in UNIX world.
1969
ii)
1972
iii)
1979
iv)
1981
v)
1982
vi)
1988
viii)
1990
vii)
ix)
1989
1990
Chapter 1 : Introduction
UNIX has a number of features, mostly good & some bad, but it is
necessary to know atleast some of them. It is indeed unique, a
product of several talented people who combined many ideas and cast
them in a simple and easy-to-understand structure.
Interactivity
Multitasking
Multiuser
Chapter 1 : Introduction
Portability
Built-in networking
Apart from the illusory effect that the system produces of a file having
absolute coordinates, UNIX doesn't really care to know the type of file
that you are using. All files are alike in the UNIX system and it
considers even directories as devices of the file system. A file to UNIX
is simply an array of bytes, and its size is simply equal to the number
of bytes that you put into it. It can contain virtually anything; text,
object code or a directory structure.
Pattern Matching
Open Systems
Chapter 1 : Introduction
Programming Facility
The UNIX shell has all the necessary ingredients like control
structures, loops and variables which establish it as a programming
language in its own right. Though the language is somewhat difficult
to learn, it has phenomenal power. The shell programming language
simplifies a number of things which are simply impossible to conceive
in other languages. It can be combined easily with the commands
and other programs in such ways that it may sometimes appear that
the two are inseparable. Proficient UNIX programmers seldom take
recourse to any other language for text manipulation problems.
UNIX is an operating system in the same way MS-DOS and OS/2 are
operating systems: software that controls the physical computer and
interprets your commands.
An operating system performs many functions :
UNIX carries out these functions through three separate, but closely
integrated parts: the file system, the shell and the kernel.
kernel
file system
shell
Two of these parts - the file system and the shell are visible to the
users. The other major part - the kernel is not really visible.
Chapter 1 : Introduction
KERNEL
10
Shell
Chapter 1 : Introduction
There are several popular shell in existence. These are C shell, bourne
shell and the korn shell (ksh). If UNIX display a $ prompt it is bourne
shell; if UNIX display a % , it is C shell .These days, because all
versions of UNIX come with both shells, users can select the shell
which they want to use.
Bourne shell
It has been named after Steve Bourne, who originally wrote it. Bourne
shell is a program and its program name is sh means it can be called
by command Sh. UNIX display $ prompt for this shell. There are flew
other versions of original Bourne shell, most notably the Bourne
Again shell ( also called bash).
Korn Shell
The korn shell (ksh) is an enhanced version of the Bourne Shell (sh).
The ksh is a sophisticated command interpreter but basically the
korn shell is same as the Bourne shell.
C Shell
C Shell has been written by one of the BSDs architects Bill. The C
shalls program name is csh. The most notable difference between the
C shell and other leading shell is that the C shell has many more
magic characters.
File System
File system is the organizing structure for data in which data is stored
in files. The organization of system Vs file system is a hierarchical file
system which resembles a tree and so sometimes it is called a tree
structured file system. The UNIX file system supports two main
objects- files with a special format, so the representation of a file is
the basic UNIX concept. Directory actually contains list of file names
so that files can be found in the file system. UNIX file system has a
root directory which is at the top of tree. This root directory can have
many sub-directories which in turn can have more sub-directories
Chapter 1 : Introduction
11
and so on. The details of the file system has been discussed in the
Unit-3.
HIERARCHICAL STRUCTURE
SECURITY
DEVICE INDEPENDENCE
The UNIX system has been ported to every major hardware vendors
machine. With over 150 designs of computers running UNIX, ranging
from micros to supercomputers, there exist differences between
various UNIX implementations. As UNIX is a multiuser, multitasking
system, it is hard to know each system requirements. Below given is
a general guideline what a user will need before starting to work on
computer.
12
Chapter 1 : Introduction
Every user who uses UNIX is given a special User login or user name
to identify the user. This login is assigned by the superuser. Super
user is the administrator of whole system and assigns new user
names and so looks after whole system. The super user of system has
the name root as user name.
To gain access to UNIX system every user has to login to the system.
This process is called loging in. To login to system, user name is to
be typed and then carriage return key is pressed.
login : smedia
password :
login : smedia
Password:
UNIX System V Release 4.0 AT&T 3B2
systemid
Chapter 1 : Introduction
13
When you login the UNIX system, youre immediately thrust into the
login shell. All the information about the shell, as well as other login
information is contained in the file /etc/passwd, as is login information
for all your user on the system.
sh k sh cshjs hbashwksh-
pdksh-
14
Chapter 1 : Introduction
After user gives user login and password to the system a system
prompt is displayed. Generally this system prompt is $.This prompt
tell the user that UNIX system is waiting for user to type a command.
Every time the system has finished running a command and waits for
further action, it replies with the $ prompt.
At the end of every line or every command which is typed in front of
$ user has to press carriage return key and only when this key in
pressed system is able to see input given by user.
It is also possible that after giving user login and password, system
can display login messages and after that it will display the $ prompt.
This login messages are usually information about system, maybe
some added features etc.
If you are the root user on the UNIX system, the prompt will be
$ echo $shell
sh
$ ls /usr/bin/*sh
/use/bin/csh
/usr/bin/ksh
/usr/bin/sh
You may want to change your prompt to appear more like the DOS
prompt. In this case you would enter the following command:
$ PSI = >
String $ to the string >, with a space at the end. The space is so that
the command you type, should not be with the prompt. The quotation
marks wont appear on the screen; only the characters between them
will appear. You can run the PSI command whenever you want it It
affects only your account, so you can personalize the string to
whatever extent tickles your fancy. For instance if you have a task to
perform at a specific time in the day, you could run a command like
the following
Chapter 1 : Introduction
15
$ passwd
changing password for smedia
Enter old password:
Enter new password:
Retype new password:
Password changed
Some UNIX system may even force to choose a new password every so
often - the official UNIX terminology is that passwords age and so
must be replaced. The system administrator can set the password
time limits. In the Rel 4 the status of the password can be displayed
by adding -s command-line parameter to the passwd command.
$ passwd -s
smedia
PW
name
passwd status
06/15/96
10
40
The final six status line directly relate to the second line which has
six answers respectively.
Security Tip
One such tools is the lock command, which is found in many but not
all versions of UNIX. The lock command locks the keyboard unless
password is entered.
$ lock
Password:
16
Chapter 1 : Introduction
Sorry
Password:
$ cal
S
7
14
21
28
January 2001
M
T
W
1
2
3
8
15
22
29
9
16
23
30
10
17
24
31
09:19:50
pst
T
4
11
18
25
F
5
12
19
26
S
6
13
20
27
date
$ cal 2001
$ date
wed Apr 4
$
1996
who
$ who
sally
smedia
mack
$
term/10Apr 4
term/07Apr 4
term/06Apr 4
9:00
9:15
9:17
This command who tells you who is using the system. The information
displayed is - user login name, systems name for the terminal they
are logged on at, and the time they logged on.
Chapter 1 : Introduction
who am i
$ who
mack
$
am i
tt3
17
Apr 4
9:17
finger
$ finger smedia
(234) 555-2333
Directory : /usr/user
Shell : /usr/bin/ksh
Last login Fri Jun 11 12:12:34 on term/07
Project : C programming
smedia
term/07Jun 12 14:23
$ finger
18
ARGUMENTS TO COMMANDS
Chapter 1 : Introduction
Filename
2.
Option
3.
expression
Ex.
Command
option
1 ) ls -al
expression
filename (s)
2 ) rm old.pat new.pat
LOGGING OUT
When youre ready to leave the terminal - its good idea to log off the
system. Why? Security, mainly. If you leave your terminal and are
still logged in, some one else could come in and tamper your
information.
To log off the system, type:
$ exit
login:
If you are bash or ksh user. If youre a C shell user, exit will work or
you can type:
% logout
logoff
bye
Chapter 1 : Introduction
19
turned off. However, there are times when you want to turn off your
system. Earlier we mentioned the shutdown state of 0. A better way
of shutting down your system is through the command shutdown. If
used correctly, shutdown will shutdown the system and alter other
users that the system is shutting down:
# shutdown
If for some reason you get an error message when you run these
commands, you may want to try specifying the full path name of the
commands. On older systems, the command line is:
# /etc/shutdown
# /usr/etc/shutdown
After using the shutdown command the system will ask you if you
want to send a message before shutting down, and how long to wait
before shutting down. It will also confirm that you really want to shut
the system down. If youre working by yourself on a UNIX workstation,
you can send a message to them, and you can give them 60 seconds
before shutting down.
With System V UNIX you can speed up the shutdown command using
the following command line parameters:
# shutdown -g0
-y
or
Reboot the computer now.
20
Chapter 1 : Introduction
iii.
Memory allocation
ii.
iv
Multiuser - means that more than one person can use the
system at the same time. The multiuser aspect comes as a
natural consequence of the multitasking feature : the system
can attend to more than one user at a time just as easily as it
can do more than the job at a time for one user.
Portability - Portability is the ability to rewrite the operating
system for a different vendors hardware without a major
rewrite effort
Built-in-network - is to link different types of computers
across small and large areas.
An operating system performs the following functions:
-
Chapter 1 : Introduction
21
Device Independence
who
co m m a n d di sp la ys t he u se r n a m e &
terminal address of those who are using
the system at that time.
date
who am i
finger
command
$ exit
$ shutdown
option
expression
filename(s)
22
Chapter 1 : Introduction
1.
3.
2.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
a)
b)
What are the three types of files used in a UNIX file system?
What two functions does the shell perform?
c)
e)
d)
f)
Chapter 2
UNIX FILE SYSTEM
THE FILE SYSTEM & GENERAL UTILITIES
THE UNIX FILE
RULES FOR FILE NAMES AND DIRECTORY
PATH NAMES
CREATING A DIRECTORY
CHANGING THE DIRECTORY
REMOVING A DIRECTORY
VARIOUS COMMANDS
24
Ordinary files
Device files
Directories
Ordinary Files
Data can be stored in any format in ordinary file. The UNIX system
views files as a stream of bytes, it reads and writes them byte by byte
or block by block, not interpreting the data and so kernel does not
impose a structure on files.
25
Directory
A directory is a storage area where any combination of files and subdirectories can be managed. Directory contents are kept in data
blocks and directories are represented by an inode in the same way
as plain files. Only inode type field distinguishes between plain files
and directories. Plain files are not assumed to have a structure,
however, while directories have a specific structure.
The first two names in every directory are , and ... New directory
entries are added to the directory in the first space available, generally
after the existing files. The file name . in a directory is a hard link
to current directory itself. The file name .. is a hard link to the
parent directory. Thus if the current directory is /user/bin/programs,
then ../bin/wdf refers to /user/bin/bin/wdf means the path is
directed towards parent directory bin.
e.g.
/ export/home/gaston
/export/home/gaston/source
source/manager.C
26
/manager.C
If current path is
/export/home/gaston
/export/home/arthur/source/
Cege.C
/arthur/source/c ege.C
..
etc
bin
tmp
home
dev
usr
lib
lost + found -
Device File
the
27
associated with the tape drive. The kernel takes care of this by
mapping special filenames to their respective devices.
Naming Convention
$ pwd
/users/home/smedia
$
28
As described earlier, the two files cant have same name and case.
Either the lettercase of the files must be different or the names must
be different. However, you can create the files of the same name if the
files are located in different directories. These different files, but with
the same file name in same case are distinguished by their pathnames.
For example consider two files Calc.report in two directories home &
smedia
/home/Calc.report
and
/home/smedia/Calc.report
These are called full path names because they provide an exact
description of the files location in the directory structure. Here the
initial slash (/) refers to the foot directory.
The following slashes separate the names of sub-directories within
sub-directories. The final slash denotes the actual file name.
mkdir Command
This command creates one or more new directories. Each new directory
contains the standard entries: .(dot) and .. (dot-dot).
mkdir
test
$ ls
jet
$
met
test
29
/
home
smedia
test
met
mack
sally
jet
Here / represents the root file system which has a users subdirectory named home under which there are 3 sub directories for 3
users - smedia, mack and sally. And user smedia has created three
sub-directories in the smedia directory.
When a new directory is created, the system builds a new inode
(information node) for the system builds a new inode (information
node) for the directory. This allows access to the data stored in the
directory file and informs the system that the file is a directory type
file.
cd Command
$ cd test
This command will change the current directory to test and now if you
type pwd command
$ pwd
/home/smedia/test
$
This will create two sub-directories pass and fail of directory test and
now directory structure will be like shown below.
30
home
smedia
test
pass
met
mack
sally
jet
fail
$ cd pass
This will make your present working directory as pass and now if you
type pwd.
$ pwd
/home/smedia/test/pass
a)
$ cd ..
$ pwd
/home/smedia/test
$ cd ..
$ pwd
/home/smedia
c)
d)
$ cd test/pass
$ pwd
/home/smedia/test/pass
$ cd
$ pwd
/home/smedia
$
31
$ cd /user/include
$ pwd
/ user/include.
$ cd
$ pwd
/home/smedia
$
rmdir Command
$ rmdir test
rmdir : test not empty
$
As test contains two sub-directories, so without removing these subdirectories, test directory cannot be removed. So to remove test
directory:
$ rmdir test/pass
test/fail
test
This command will first remove pass sub-directory and then fail subdirectory and after that test directory is removed.
$ ls
jet
$
met
$ rmdir -p /test/pass/fail
32
rmdir command with flag -p removes all directories along the path
name specified by the directory parameter. This first removes the /
met directory and then the /jet and
/test directories in order. If
a directory is not empty or does not have write permissions when it
is to be removed, the command terminates.
ls Command
a)
$ pwd
/home/smedia
$ ls
identity jet
met
b)
met
$
d)
e)
true
$ ls -a
.
..
c)
new
new
true
.prof
identityjet
$ ls -A
This lists all entries in the directory except . ( dot) and ..(dotdot). The result is same as in the Ist case because this flag A is used by default.
$ ls -C
$ ls /
f)
g)
h)
i)
j)
33
This will display the root file system. Here the/ means the root
of directories like - home, usr , var, bin, libh, dev, lost+found
etc.
$ ls - x
$ ls -m
$ ls -p
identity
$
jet/
$ ls r
true
$
new
met/
new
This command puts a slash { /} after each file name if that file
is a directory. Here it has put / after two directories jet and
met.
met
jet
identity
Suppose you have a file named average under met subdirectory and to list all sub-directories recursively and to list
all sub-directories recursively, this command can be used.
$ ls -R
identity
./jet:
./met:
average
jet
met
new
k)
true
true
$ ls -1
identity
jet
met
new
true
$
34
l)
This forces output into one entry per line format. This is the
default setting when the output is not directed to a terminal.
$ ls -l
total 48
-rw-rr
drwxr-sr-x
drwxr-sr-x
-rw-rr
-rw-rr
$
1 smedia
3
3
1
1
smedia
smedia
smedia
Smedia
gp
gp 512
gp 512
gp 1
gp 512
Jul 26 11.41
Jul
Jul
Jul
Jul
26
26
26
26
12:20
12.01
12.21
11:45
identity
jet
met
new
true
File modes
3.
Owner name
2.
4.
5.
6.
7
File Modes
No. of links
Group Name
file size
The very first column displays the information about the file modes.
This information consists of 10 characters which varies from file to
file.
If the first character of information displayed is d
->
->
b
l
->
->
->
->
The next nine characters are divided into three set of three characters
each. For every file and every directory in the file system, there are
three classes of following users.
1. Owner
2. Group
35
The three characters in each set indicate, respectively read, write and
execute permissions of the. So there are three basic authorizations.
r (Read)
w(Write)
x(Execute) -
e.g.
rw-rr
rwxr-xr-x
rwxxx
rwxr-sr-x
No. of links
This is same as in 2nd example. Here the group s execute permission character is as the file has
set group-ID mode.
No. of links for files is usually 1. If this no. is more than 1, it shows
that a number of identical copies of the file exist in different places
on the system. For directories, the number of links is an indication of
number of sub-directories in that directory plus two ( one for
directory itself and other for parent directory).
36
Name of Owner
Shows the owner of the directory or file. In this case the users or
owners name is smedia.
Name of Group
This shows the group of users that the owner is part of. In this case
the user smedia belongs to group called gp
Size of file
This shows the size of file in bytes. For text files the size of file is the
number of characters in the file.
Name of file
m)
$ ls - al
total 64
drwxr-sr-x 1 smedia
drwxr-sr-x 1 smedia
-rw-rr 1 smedia
drwxr-sr-x
drwxr-sr-x
-rw-rr
-rw-rr
3
3
1
1
smedia
smedia
smedia
Smedia
gp 512
gp 512
gp 1
gp 512
gp 512
gp 1
gp 512
Jul 31 12:36
Jul 28 15:35
Jul 26 11.41
Jul
Jul
Jul
Jul
26
26
26
26
12:20
12.01
12.21
11:45
.
. .
identity
jet
met
new
true
Description
-X
-r
-F
-I
-a
-d
-t
-R
-u
-i
-l
-s
37
group Command
To find out the groups, you are assigned to, groups Command can be
used
$ groups
gp
group1
$
The above information tells you that you are a member of gp and
group1 group. Information about groups and their member can be
found in /etc/group file, which is readable file. However, on a large
system, this file could be extremely large so grep command (will be
discussed in detailed at a later stage) can be used:
gp
: 120 : smedia, Hare,
group1 : 421 : Kathrine, smedia, John
$
The above information display the member of each group and the
group IDs(120 for gp, 421 for group1). The information is important,
if the group is to be switched during normal work. The group can only
be switched if you are member of the new group. That can be done
using the newgrp command.
$ newgrp group1
$
chmod Command
As discussed earlier, the first column (last when read form right to
left) display the permission to different levels of permission. There are
read, write and execute.
The above three permission can be applied to files as well as directories.
When applied to files, read permission means that the you can change
the file and the execute permission means that you can run the file
as a program.
38
100
200
040
020
010
004
002
001
You get the numeric form by adding together the number and then
combining that member with chmod command. (short for change
mode).
Consider the following example:
-rwxrr
smedia
gp
Jul 26 11.41
identity
The above Symbolic form can be translated to numeric form a follows400 (r)
100 (x)
200 (w)
040 (r)
004 (r)
____
744
39
The above command will change the permission for the file identity to
everybody ( including owner, group and all users), the following
command can be used :
The above command will change the permission to where only the
owner has the ability to read write and execute file identity.
The above command will change the permission to where the owner
has the ability to read, write and execute the file, with members of the
group also having the ability to read, write and execute.
To change the permission of the contents of the entire directory with
chmod, -R can be used as a switch.
Other
+
-
w
x
e.g.
$ ls -l identity
-rwxrr
group
smedia
gp
40
The above command will add the executable permission to the group
and takes away the readability permission form all users.
$ ls -l identity
-rwxrr
smedia
gp
i.e.
umask Command
$ umask
744
$
To changed the default permission the parameters are given along the
umask command, but it must be noted that within the UNIX system,
the umask command changes permission relative to a baseline of
777. Thus the command umask 007 is giving input the baseline 770,
thus giving a final permission of 770.
$ umask 007
$ umask
770
$
41
Even if you take other more advanced security steps (as youll learn
about when you learn about networking and communications), your
data may still be vulnerable. Plan accordingly.
cat Command
A file can be created by typing cat > filename and pressing RETURN.
Then contents of file can be typed and Ctrl-D (Ctrl-D is the UNIX endof-file marker) is pressed to end this file.
:
:
:
smedia
KJ-75, Kavi Nagar, Ghaziabad.
3
Here the > symbol informs shell to redirect output (discussed later)
of the cat command to a file identity.
Now to display the contents of above file type -
$ cat identity
Name
:
address
:
Age
:
$
smedia
KJ-75, Kavi Nagar, Ghaziabad.
3
42
$ cat identity
Name
:
address
:
Age
:
Phone No.
Copying a file
smedia
KJ-75, Kavi Nagar, Ghaziabad.
21
001 - 0120 - 4702867
This will copy the old file into the newfile. The command is a
combination of cat reading the source file and the shell redirecting
the output to a file.
Concatenating Files
To display more than one file, simply name more than one file on the
command line.
Here first four lines are from file identity, next one is from file new and
last line is from file true. So there is no notification of when a file ends
and the next one begins. The input is combined into one contiguous
output stream
Instead of sending this displayed information to terminal, it can be
sent to a file by using
Now you will get the new files which contains contents from identity,
new and true file.
43
pg Command
$ pg filename
more Command
While viewing large files, you often find the output scrolling off you
screen. This sometimes happens so fast that, before you hit <Controls> to stop it, quite a bit of the output would have scrolled off. Using
<Control-s> and <Control-q> alternately is certainly not a comfortable
method of halting the output. It also doesnt let you see what has
already been seen before. UNIX offers the more command as a paging
tool, so that you can view one page at a time.
A product of the University of California, Brerkley, this command has
now made its entry into several versions of UNIX (especially XENIX).
It is now offered in Release 4. Based on pg, the original pager of the
UNIX system, more, allows the user to view a file, one screen at a time.
This chapter present more, in preference to pg. Because it is in may
respective superior to pg. For installations not having more, use pg.
instead, which is similar in operation.
The syntax of the more command is a follows :
You really don't need to use more compulsorily with such a complex
command line, except for the filename (strictly speaking, even that is
not), the rest are optional. To view the file chap01, simply enter the
command with the filename:
$ more chap01
You will see the contents of chap01 on the screen, one page at a time.
Normally, the message ...More..., along with the percentage of the
file tat has been viewed, is displayed at the bottom of the screen. But
there can be variations in the message it displays, depending on the
brand of UNIX you are using. You can advance to the next page by
pressing the spacebar (or <Enter> in some cases). To quit the more
program, simply press q (quit).
44
You first see the contents of the first file, preceded by its name. After
you have finished viewing this file, more pauses with the message
.....More...(Next file : chap02) , before displaying the contents of the
file chap02. In this way, it sequentially displays all the files, pausing
additionally whenever a change of file occurs.
More has a couple of internal commands of its own, which dont show
up on the screen when you invoke them. In other words, you can use
certain key sequences inside the more program to act on the output.
Many UNIX utilities like ex, vi, mail and sed also have their own
internal commands.
In the middle of a session, you can always switch to the next file, by
entering the two-character sequence
:n
:p
At any time, you can know the filename, as well as the line number
that you are on, by using
:f
/UNIX
If that is not the pattern you are looking for, then you can press n
repeatedly till you have located the desired line. The mechanism of
locating a pattern and repeating a search is identical in the vi editor,
also from Berkeley.
file Command
$ file emp.Ist
emp.Ist:ascii text
$-
45
When the command is used to apply to all files in the progs directory,
you will see an informative list (use the *again to indicate all files) :
$ file progs/*
abcd:
ascii text
calender
compchk.sh:
helpdir:
textl;
progl.C
$-
English text
commands text
directory
date
c program text
od Command
$ cat odfile
White space
$ od -b odfile
0000000 127 150 151 164 145 040 163 160 141 143 145 040
When used with the -b option each line displays sixteen bytes of data
in ASCII octal format, preceded by the position in the file of the first
line contains the letter W, which also has the octal value 127. This
methods of identifying characters may not be attractive enough to
warrant the extensive use of od, but when combined with the -c
(character) option, the output is friendlier :
$ od -bc odfile
0000000
cp Command
W h i t e
s p a c e
127 150 151 164 145 040 163 160 141 143 145 040
46
specifies the name of file or directory to copy from, and the second
argument is the target file or target directory parameters which
specifies the name of file or directory that we want to be the copy cp
commands can copy.
A directory to a directory.
If the file specified by target file already exists, the copy writes over
the original contents of the file so be careful, when this command is
used. Files maintain their respective names when copies to a directory
unless you specify a new name file at the end of path.
a)
$ pwd
/home/smedia
$ ls
identity
jet
met
$ cp identity identity.doc
$ ls
identity
b)
identity.doc
jet
new
true
met
true
$ cp p identity true.doc
c)
$ cp identity /home/smedia/met/identity.doc
$ ls met
average identity.doc
To make a copy with the same name do not give the target file name.
d)
$ cp identity
$ ls met
average
/home/smedia/met
identity
identity.doc
e)
47
$ cp -R /home/smedia/jet /home/smedia/met
f)
$ cp
new true
/home/smedia/jet
$ cp /home/smedia/met/*.doc .
This will copy all the files in met directory, to the present working
directory, signified by the single.(dot).
mv Command
a)
$ mv new new.doc
$ mv - i true new.doc.
overwrite new.doc? n
$
b)
$ mv jet met
48
c)
$ mv new.doc jet/new1.doc
d)
This moves file new.doc from current directory and same file
appears with name new1.doc in pass directory.
To move a file to another directory, keeping the same name,
enter:
$ mv
$
e)
true jet
$ mv jet/*.doc .
$
This moves all the files with extension *.doc into the current
directory with the same names.
$ mv jet/* .
$
This will move all the files and sub-directories from jet directory
to current directory and will empty jet directory.
rm Command
a)
b)
c)
$ rm identity.doc
$
This command will remove all five files from current directory.
If any of these file does not exist, then it will display a message
that A file or directory in the path name does not exist.
To delete files one by one, enter
$ rm - i
$
fail/*
49
this command can remove only the files within this directory
and if this fail directory contains any sub-directory will
display the message that this directory cannot be removed
like for above it will display -
rm
rm
rm
d)
rm
: remove jet/average ? y
: Remove jet/identity ? y
: Remove jet/identity.doc ? y
$ rm -ir
$
met
This command recursively removes the contents of all subdirectories of the met directory, and prompts you regarding
the removal of each file, and then removes the met directory
itself. If you deny permission to remove a sub-directory, the
rm command does not remove the met directory.
WILDCARDS
$ ls * report
a.report b.report
smedia.report
These three files represent the number of files in the current directory
ending in the string report.
$ ls report *
report.new
report.old
reporter.old
If you wanted to list the files with the string report some where in the
filename, use:
50
$ ls *report*
a.report
newreport91
oldreport92
b.report
newreport92
report.new
reporter.old
smedia.report
oldreport91
report.old
Note that weve received a list of files that both end and begin with
report, as well as the files with report in the middle of the filename. As
we said, the * wildcard can be used to match any number of
characters in a string. In this case the wildcard matched zero
characters.
Conversely, the ? wildcard is used to match a single character in a
string:
$ ls report?
report1
report2
report3
report4
$ ls ? report*
lreport1991
2report 3report92
The final wildcard option is denoted by brackets. Here you can ask
UNIX to match specified characters:
$ ls report199[01]
report1990
This becomes especially useful when youre looking for files and
youre not entirely sure of the case (remember, UNIX distinguishes
between uppercase and lowercase characters) :
$ ls report[a-d]
reporta
reportb
reportc
reportd
This command did not return filename reporte, because it did not fall
in the range of characters defined within the brackets.
51
$ ls */*
Arguments too long.
$ ls [A-Z] */*
Then ask for all files in directories that begin with lowercase letters:
$ ls [a-z] */*
Whatever method you use, you must find a way to divide up the
number of files passed on the command line.
Even through weve lectured you about the necessity of good file
organization, its inevitable that youll lose track of a file - and usually
the more important the file the more likely youll lose track of it.
UNIX features a powerful command, find, that helps you locate the
wayward file. Lets say that youve misplaced a file named 2001.data.
If youre truly masochistic, you use the following command to find it:
In this case UNIX searches for the file 2001.data in every directory
and sub-directory in the entire system. If youre working on a large,
multiuser system with hundreds of megabytes of storage space, it can
take quite a while to find this file - especially given the fact that
2001.data is not exactly a distinctive filename and that theres a very
good chance that another user may have appropriated the same
name. Even on a single-user system with 300 or 600 megabytes of
hard-disk space the search can take too long.
Its best to use the find command with some limitations, such as
specific directories. Lets say we know that the file 2001.data is
located some where in the /user directory. We user the following to
narrow the search criteria:
Lets say you dont remember the exact name of the file; you know that
you created it sometime in the 2000s but dont remember the exact
year. Since youre an organized user and denote all your files with the
year as a prefix, you could use a wildcard to search for all files
beginning with the string 200:
52
When using the -name option, be sure to enclose your search string
in quotes. UNIX is rather quirky on this point and perhaps over
complex. The reason for this is that the command interpreter ( called
shell in UNIX parlance) would expand the 200* to mean the name of
every file in the current directory that starts with 200 - which is most
definitely not what you intended.
This tells UNIX to search for the file 2001.report beginning at the top
of the file structure with the root directory and moving downward,
and alerting you when the file is found. The ampersand (&) tells UNIX
to perform this task in the background .
However, you may not want to be alerted when the file is found,
particularly if there are potentially many instances of the file. To print
the results to a file instead of to your screen, insert the > symbol as
well as a filename in the command:
This directs the output of the search to the file results. In general, the
> command will direct the output of a command to a file; well use the
> command may times throughout the course of this book.
There are two ways in which we can have the output from the
computer.
Softcopy
Soft copy is the copy of a file that is stored on a disk somewhere in the
file system. It exists as electronic or magnetic patterns somewhere in
the computer system.
Hardcopy
Hardcopy is the copy of a file which is taken with the help of printer
on a paper. It exists in the real world. It can be run, can be felt, and
can be seen, can be felt, and can be read and thats why it is called
hardcopy.
Here we will take two commands lp and lpr to print the files.
53
lp Command
This command responds with a line of text which tells you what
identity has been allocated to your print request. This number will be
required when you later decide that you do not want the printout after
all.
a)
-n option
$ lp -n 3 tfile
b)
- m option
c)
- w option
lpr Command
$ lpr filename
b)
$ lpr file*
After running this command also the system will list the print
and will generate an ID number so that if user can check the
status of printing at a later line.
This command will print all files that begin with the string
file.
lpstat Command
a)
$ lpstat
54
b)
$ lpstat - t
cancel Command
The cancel command cancels line printer requests that were made by
the lp command. Syntax of this command is
$ cancel 173.
This command will cancel the printing of file with job ID No. 173.
banner Command
#
#
#
$ -
#
#
#
#
#
#
#
#
#
###
#
#
###
#
#
This is the size used by lp to print the user name on the title page.
There are no options, and it is simple to use.
55
Special file
3.
2.
4.
5.
cp command can also be used to copy the files from one file
to another, from one directory to another etc.. mv command
can be used to move the file from one place to another. rm
56
a.
c.
b.
4.
5.
a.
c.
b.
d.
3.
57
a.
c.
b.
a.
c.
b.
d.
a.
c.
b.
6.
a.
7.
a.
c.
Write
t h e com m a n d t o d i s p l a y n o n - p r i n t a b l e
characters.
b.
b.
d.
e.
8.
9.
new letter
c)
a.b.c.d.e
b)
e)
f)
58
10.
c)
b)
d)
e)
f)
11.
g)
13.
14.
b.
12.
How could you restore write permission for yourself and for
other group members for the file oddities?
Chapter 3
UNIX TOOLS
UNIX TOOLS
FINDING TEXT PATTERNS IN A FILE(S)
SORTING FILES
SPLITTING A FILE APART
FILE COMPARISONS
CUTTING FILES
MERGING FILES
COUNTING THINGS IN A FILE
CHECKING SPELLINGS
VIEWING NON-ASCII FILES
60
grep Command
Weve all done it: needed to find a nugget of data and couldnt
remember exactly where we stored it. Instead of manually searching
through the hundreds of files on our system, we can invoke three
UNIX tools : grep, egrp and fgrep.
The grep in a utility program that searches a file, or more than one
file, for lines which contain strings of a certain pattern. Lines which
match the specified pattern are printed on standard output.
a)
b)
c)
99, G.T.Road
Ghaziabad
Ghaziabad
a)
b)
c)
61
Limited
Ghaziabad
Grep searches one line at a time. If, in our example, Ram and
Ganga had appeared at two different lines, grep would not
have reported a match.
Grep looks for strings of text and does not limit itself to the
whole words. A search for the string town could return the
lines containing the words mini-town, downtown & town.
$ grep Ga* *
d)
e)
If you dont want grep to list the lines of text matching the
specified string, use the -l(ell, not one) option to list only the
file names.
f)
person
$
Ghaziabad
Delhi
62
egrep Command
While egrep supports all the function of grep, it goes a step further
and allows the searching of multiple strings. For example, multiple
companies are to be searched in the same file. It can be done by
combining the names of the companies with a pipe symbol within
quotation marks:
fgrep Command
Ghaziabad
Ghaziabad
fgrep (shorthand for fast grep) works similarly to egrep, but instead
of using a pipe command and quotation marks to specify the text,
each item must be placed on its own line.
Computers
4, Gandhi Nagar
99, G.T.Road
sort Command
Limited
Ghaziabad
Ghaziabad
$ cat Code
DELHI
CALCUTTA
BOMBAY
MADRAS
$
011
033
022
044
$ sort code
BOMBAY
CALCUTTA
DELHI
MADRAS
022
033
011
044
63
$ cat person
RASHMI SYAL
100
SANJEEV CHAWLA
RICHA VASISTHA
CHARLIE SMITH
AMBICA CHAWLA
99
125
114
105
$ sort +1 person
SANJEEV CHAWLA
AMBICA CHAWLA
99
105
RASHMI SYAL
CHARLIE SMITH
RICHA VASISTHA
100
114
125
Each line in the file is considered to consist of fields, the fields being
separated by spaces. So to get file in order of last name, program is
told to skip one field [the first names] by specifying it by +1.
To sort first on last names and then on first name, type :
$ sort +1 -2 person
AMBICA CHAWLA
SANJEEV CHAWLA
RASHMI SYAL
CHARLIE SMITH
RICHA VASISTHA
105
99
100
114
125
99
100
105
114
The above command skips one field before it starts sorting [ first
names], then it stops sorting after the second field [last names]. When
sort stops sorting after the second field, it then resumes sorting from
the beginning of line again, so it sorts on first names and rearranges
names AMBICA & SANJEEV.
VASISTHA
125
64
person
OR $ sort +1 -2
Here the contents of all the files named are joined together, end to
end, and the composite is then sorted.
If input files are already sorted, it can be merged by using the -m
[merge] option.
$ sort -u
65
split Command
This command will split a file into pieces. This command is useful to
split big files which are too large to fit in the help of editors.
a)
b)
$ split bigfile
This command will split begfile into 1000 line segments and
each part gets put into a different file in the current directory.
The names of output files are generated by using the letter x,
followed by two more letters. The first output file name will be
xaa and so on through xaz and then xba and so on right
through xzz. Each of the file produced except the last, will
contain 1000 lines. The no of lines in last file will be whatever
was left over a multiple of 1000.
To control the number of lines in the output file, following
command should be typed.( The option is -l(ell, not one)).
This will split big file into 50 line segments named sectaa,
sectab, secac, and so forth.
In UNIX many new files are created during the course of updating
older files. And if you are not perfect at your file-management duties,
the end result may be a set of files that are similar but contain small
differences as a result of editing and revisions.
UNIX contains several tools that compares files : cmp, comm, diff
and dircmp.
comm Command
CALCUTTA
DELHI
MADRAS
$ sort +1 code1 > code1_out
CHANDIGARH
CALCUTTA
DELHI
GHAZIABAD
$ comm code_out code1_out
66
BOMBAY
CHANDIGARH
MADRAS
GHAZIABAD
CALCUTTA
DELHI
The cmp command compares two files and tells if the files are
different. If they are, cmp reports the first instance of a difference.
Cmp does not report all the differences between the files and it will
report nothing back if the reports are the same. After we sneak a peak
at two files, (using cat command), we can see how cmp works.
$ cat letter1
Dear Rashmi:
Immediately send the information regarding program.
NN
$ cat letter2
Dear Mini:
Immediate send the information regarding program.
Also enclose the return ticket MN.
$ cmp letter1 letter2
letter1 letter2 differ : char 7, line 1
Thus cmp command reports that the two files differ in the sixth
character of the document, located in the line1. Using cmp is the
simplest and quickest way to compare the two files.
On the other hand, the diff command compares two files and tells you
if they are different along with the differences in the lines.
67
n1,n2dn3
< line n1
< line n2
n1an2,n3
< line n2
< line n3
dircmp Command
$ ls jet
identity
new
$ ls met
identity
true
68
The first listing jet only & met only states the files and directories
that are only in either jet subdirectory or met subdirectory. If the
names appear in the first column, it means they are in first directory
i.e. jet. If the names appear in second column, it means they are in
second directory only i.e. met.
The second list Comparison of jet met is a comparison of files with
the same name in the jet & met subdirectories. There are three
possibilities in this listing.
directory
different
same
name
name
name
The first signifies the two names are directories. The second states
that the contents of the two files are different. The third states the
contents of the two files are the same.
cut Command
$ cat rec_emp
RASHMI SYAL
SANJEEV CHAWLA
RICHA VASISTHA
CHARLIE SMITH
AMBICA CHAWLA
100
99
125
114
105
CHANDIGARH
DELHI
LUCKNOW
BOMBAY
CHANDIGARH
284955
235678
873455
746555
234455
69
Here, the cut command will cut first & third field in the file rec_emp
and send the output to the file rec_emp.1 .
To define the range of fields, say 1,2 and 3, we could use the following
command.
If the files are not highly structured (here tabs has been used to
separate the columns) and the fields are separated by another
character say #, we would need to simply specify the character using
-d option:
paste Command
Paste command joins together two or more files line by line; that is,
the first line in the second file will be pasted to the first line in the first
file.
join Command
A better way of merging files, provided that the files contain one
common field, is through the join command. Consider the following
two files to be joined.
70
RASHMI SYAL
SANJEEV CHAWLA
RICHA VASISTHA
CHARLIE SMITH
CHANDIGARH
DELHI
LUCKNOW
BOMBAY
AMBICA CHAWLA
CHANDIGARH
$ cut f1,4 rec_emp > rec_emp.2
$ cat rec_emp.2
RASHMI SYAL
284955
SANJEEV CHAWLA
235678
RICHA VASISTHA
873455
CHARLIE SMITH
746555
AMBICA CHAWLA
234455
$ join rec_emp.1 rec_emp.2 > rec_emp.fin
$ cat rec_emp.fin
RASHMI SYAL
CHANDIGARH
SANJEEV CHAWLA
DELHI
RICHA VASISTHA
CHARLIE SMITH
AMBICA CHAWLA
LUCKNOW
BOMBAY
CHANDIGARH
284955
235678
873455
746555
234455
By default the join command will work only when the first field of each
file match and are sorted identically. The files can be joined on the
basis of fields other than the first in each files. The following would
join two files based on the second and fourth column :
Here -j option is being used for joining the two files. -j1 2 refers to the
second field of first file and -j2 4 refers to the fourth field of second
file.
Global replacement
There are times when we may want to change repeating parts of a file.
To do so tr command can be used to search and replace the specified
strings.
Suppose the tabs in the file emp_rec are to be replaced by comma(,).
This could be done by the following command:
71
wc Command
$ wc code
5
15
125
code
The first number is the number of lines in the file. The second number
is the number of words in the file. The third number is the number of
characters. [including new lines] in the file. Finally, we displays the
name of the file it found.
We can have three options 1]
-l option
3]
-c option
2]
-w option
$ wc - lc code
5
$
125
code
spell Command
UNIX spell can be used to check the spellings in the file. Spell is
intended to work with UNIX pipes and input redirection, so spell
supports a very primitive interface. But the limitation in the spell is
that it can tell the word which is misspelled, but offers no suggestions
for the proper spelling. The syntax of the spell command is as
follows:
$ spell filename
Spell will then examine all the words in the given file and print out
a sorted list of all the words spell flagged as errors. Its upto you to
search for these files in the original file and make corrections, using
the text editor (vi or emacs).
strings Command
Cat command can be used to view the file contents, which has been
discussed earlier. However, cat command is limited to display the
72
$ strings program
73
The grep command and its brethren fgrep and egrep search
text files for words and phrases. Grep searches for text in
either single file or any number of files you specify. It goes
through the file and returns the lines containing your specified
text. The text can be single word or a string surrounded by
quotation marks. The basic syntax for the grep command is
$ grep phrases to look for filename_to_search
74
3.
a.
c.
b.
a.
c.
b.
a.
b.
c.
4.
5.
6.
a.
c.
b.
a.
c.
b.
a.
c.
b.
d.
e.
Chapter 4
REDIRECTING OUTPUT
STANDARD FILES
REDIRECTING THE STANDARD OUTPUT
PIPES
76
STANDARD INPUT-
2.
STANDARD OUTPUT -
3.
$ ls -l > contents
$
$ cat contents
Now you can see the contents file, which will have the output of ls l command. In this output, it will display the name of contents file
also but the file size will be zero. The reason for this is that it is the
shell which creates the file to receive the commands output, and it
does this before the command runs.
This will add the name of current working directory at the end of file
contents.
But if you append a file which does not exist , then this command will
display a message saying that the file does not exist.
77
Symbol
Usage
>
<
>>
command1 | command2
Result
$ command1 | command2
78
The above command searches for all files ending in .c in the current
subdirectory, searches these files for the string arg, and then prints
all the lines containing arg.
Although there is no limit on the number of pipelines, longer
pipelines can be confusing and harder to identify. The shell allows to
divide a long pipeline into several easier to read components. The
previous command could be written as follows.
$ ls *.c |
> grep arg |
> lp
Here, > sign tells that shell is waiting for additional input from the
user. The > is a secondary prompt, or PS2. Since the initial command
ended with a pipeline command, the shell correctly assumes that
there is more input coming, otherwise, you would be generating an
error with the incorrect use of pipe command.
The shell also uses standard input and output to send you error
messages, technically speaking, they are known in UNIX parlance as
standard error. Standard error is sent to screen by default - the most
logical place for it.
Error messages can generate under a variety of circumstances. Since
the default with most UNIX commands is sending output to your
screen, it makes sense that all error messages related to the command
are sent to your screen. However, the shell goes a step further and
sends all error messages to the screen, even those related to the file
operations that dont normally generate any response. Consider the
above example, with no .c files available in the present working
directory:
Without this response, youd never know exactly why the command
failed.
79
$ command1 | command2
80
3.
2.
4.
b)
c)
d)
e)
Chapter 5
COMMUNICATION IN UNIX
COMMUNICATION & ELECTRONIC MAIL
CONTROLLING MESSAGES
THE PAPER-FILLED OFFICE
SENDING MAIL
RECEIVING MAIL
THE INTERNET
CREATING MAIL
HANDLING MESSAGES
SAVING MESSAGES
82
When a message is sent to a user who is not logged in, the message
user not logged in appears. If the message is sent to a user who has
refused message permission by setting mesg command to yes, the
message permission denied appears.
a)
$ write mack
$ write mack
Press the enter key and type,
$ write smedia
I am running tests at 12.30 can we meet at 3?
O
And smedia might respond:
c)
83
Here O-O means over and out, telling mack that he has
nothing move to say. If
mack is also finished O-O, then
both can press Ctrl-D to end the conversation.
mesg Command
a)
$ mesg n
$
b)
c)
Permission denied.
$ mesg y
$ mesg
is y
As you can tell by looking at the pile of papers, faxes, and folders
strewn across your desk, the day of the paperless office hasnt yet
84
The mail program has been an important part of UNIX almost since
the very beginning. As UNIX evolved, so has mail- to an extent. The
actual electronic-mail mechanisms are similar to the original mail
mechanisms: changes mainly concern how a user interacts with a
mail program. The procedures described here may not appear exactly
the same on your system, as there are a large number of mail
programs, both UNIX and XWindows -based that vary in how they
present information to the user.
mail is the UNIX facility where users can send messages to each
other, such that the messages get collected in a mailbox somewhere
in the system.
1-
b)
If at this time user does not read the mail , user will get
the same message
85
System mailbox
Personal maibox.
$ mail
mail version 4.0 Type ? for help.
2 messages:
The shell responds with a list of your mail messages, listed in the
order that they were received by your system, newest mail first. (
These messages are usually contained in the file /user/mail/
yourname, /usr/spool/mail/yourname, or /usr/spool/meuque/
yourname.).The first field lists the sender of the message, the second
through fifth fields denotes the time and date the message was
received, the sixth field records the number of lines in the message
and the size of the message ( in bytes), and the final field indicates the
subject of the message.
Press Enter to read the first message on the list. If its a long
message, the entire message will scroll by. If you want to stop
scrolling the message, type Ctrl-S to start it again, type Ctrl-Q. There
are two types of messages waiting for us:
86
Your electronic mail can come from two sources - Your own system
and from other systems.
Mail from other system, sent on Internet or Usenet, has its own
addressing scheme (more on that in the next section). Mail from your
own system uses the same login names as described earlier in the
chapter. These names are contained in the /etc/passwd file.
First we will concentrate on the mail sending & receiving from your
own system.
a)
$ mail mack
Hi, How are you?
I have brought the two tickets for movie if you are free,
we will meet in evening to discuss the program in detail
^D
$
b)
c)
and then the message is typed and will be send to both mack
and sally.
d)
$ mail mack
Inform me about your evening program
^D
Mail : Cant send to mack
Mail saved in dead.letter
$
If you
or by
saved
again
e)
$ rm dead.letter
$
87
Means there is no mail for smedia But if smedia has some mail
, then if you type mail
$ mail
from mack wed jun 11 12:30 1995
f)
$ mail - f
The first and older scheme is called a bang pabb, first popularized on
the Usenet, which makes up part of the internet. Essentially youre
telling the mail system the exact route it must take to send you mail
. This can be a gigantic pain, especially if there are many machines
a message must go through before it is delivered. Luckily this manual
addressing of electronic mail is on the wane, which is why you see so
few electronic- mail addresses dotted with exclamation marks.
Still, theres a need for bang paths when it comes to electronic mail.
Many users now take advantage of gateway, which forward mail to
other connected machines. If you have access to a gateway (check
with your system administrator; chances are that you do if you have
the ability to send and receive electronic mail from the internet), you
can just send mail to the gateway, denoting the system name and the
user name:
$ mail unnet\!concubine\!kevin
88
$ mail unnet\!concubine\!kevin
The previous command tells the C shell that you really means to use
the exclamation mark (!) and dont want csh to look in its record of
your previous commands.
rahul refers to the user, while mr.net refers to the domain. The user
and domain names are separated by the at @ symbol. As a user, you
dont need to know the specific path a message must take, nor do not
need to know the name of a gateway. With a domain address, sending
a message is simple.
$ mail [email protected].
The idea of the internet is fairly amorphous and abstract (You didnt
think we could make it through a chapter without a little abstraction,
did you?). The internet is technically a collection of many networks
that somehow manage to talk to each other. As a user, all you need
to know is a recipients electronic mail address; the system
administrator handles the basic details of linking a system to the
internet.
$ mail [email protected]
89
As always, end input from the keyboard by typing Ctrl-D. Some Email programs also accept a single period on its own line to terminate
the message, instead of Ctrl-D. The procedure would be the same if
you were sending a message to a user on a remote machine.
You can send the same message to multiple users with the -t option:
The resulting message will contain multiple To: fields in the header.
The Berkeley UNIX mailx program allows you to call up a text editor
from within mailx, by using the ~v command. You must start this
command on its own line.
$ mailx kevin
~v
Where binaryfile is the name of the binary file you wish to send. The
resulting message will have a line in the header signifying that the file
is binary.
90
Asking for a response related to the mail program. There are many
actions that you can take at this point: the handiest options are listed
in following table
Command
Result
RETURN
df
dN
dp
dq
uN
s filename
w filemane
?
?s
Lets say youre working on a project with user smedia, and you want
to keep all of his mail message in the same file. You do so with the s
option at the prompt.
? s smediamail
Where smediamail is the name of the file containing his mail messages.
When you do this the first time, the shell creates a file named
smediamail. Subsequent uses will append mail messages to the
existing smediamail file. To read this file, use mail with the -f option:
$ mail -f smediamail
91
$ mail smedia
Subject : test
Appear in the test.
^D
$
92
a.
c.
b.
d.
e.
f.
g.
2.
a.
3.
a.
4.
b.
b.
a)
b)
c)
d)
e)
Chapter 6
TEXT PROCESSING
TEXT EDITOR VI & TEXT PROCESSING
VI EDITING MODES
MOVING WITHIN A FILE
CHANGING TEXT
SAVING CHANGES TO A FILE
94
Command Mode
This mode is used when text is added. Text input mode is entered with
any of the following subcom mands - the a subc omm a nd , A
subcommand, i subcommand, I subcommand , o subcommand, O
subcommand, C subcommand, s and S subcommand, R subcommand.
After entering one of these subcommands, text can be entered into the
editing buffer. To return to command mode, ESC key is pressed for
normal exit or Ctrl-C to end abnormally.
CALLING UP VI EDITOR
Vi editor is called up by -
$ vi textfile.
95
After typing this, a file is read into the edit buffer, the terminal screen
is cleared, the window is set at the first line of buffer, and cursor is
initially set at the first character of first line in the window.
Up arrow () or k
Down arrow () or j
Right arrow () or l
fx
Fx
tx
Tx
;
,
Moving to Words
W
B
E
96
Z
z.
Ctrl-F
Ctrl-D
Ctrl-B
Ctrl-E
Ctrl-C
Z+
Z\^
Pages down.
97
A text
i text
I Text
I t i n s e r t s t e xt s p e c i f i e d b y t h e t e x t
parameter before the cursor. Text input
mode can be ended by pressing ESC key.
I t in se r ts t e xt s pe cif ie d b y th e Tex t
parameter before the first nonblank
character in line and to stop text entry ESC
key is pressed.
ESC
Ctrl-W
98
Command Mode
CW
Changes a word.
CC
CW Text
D
dd
dw
J
rx
R text
s
<<
>>
\^
Changes a line.
P
xp
xd
y
xy
y
:W
:W file
99
:e file
:e + file
:C # or Ctrl -A
:e !
100
:q!
ESC
Ctrl-?
If you want to run a UNIX command from within vi, by typing the
usual colon[:], followed by an exclamation mark [!] followed by
command which you want to run.
If there are several such commands in a row, it in better to enter the
shell from vi. This can be done by typing either : sh or just : sh. At
this point, you can see the system prompt [$] and many commands
can be executed.
When you want to return to vi session, it can be done by typing CtrlD, and you will come back to vi session at the same point in the file
as you left it.
TEXT PROCESSING
One of the most popular publishing software in the world, troff and
its pre-deccessors are essential tools for any UNIX user who wants to
create professional -looking documents and dont want to shell extra
for a professional package. These tools come with most versions of
UNIX although sometimes theyre split out into a package called the
Documents Workbench.
101
Troff is like a word processor where you can input text and then
manipulate it. In the true UNIX tradition of dividing processing tasks
to free the user from too much interactively with the system, you
create a text document in a text editor like vi or emacs insert the
proper formatting commands there, and then run your formatted
document through troff.
The best way to explain troff is to look at before-and-after as shown
below.
$ troff test
Or, better yet, go ahead and redirect the output of troff a file.
$ cat test.tr
If system has a printer connected, go ahead and print the result of the
troff command. Use troff and then redirect the output to the printer:
.ce n
.bp
.fi
.ft n
Page break.
102
\fn
Change font to n.
.ls n
.in n
.na
.nf
.pl n
.po ni
.ps n
\Sn
.sp n
.ti n
.un n
103
Unix uses text files for just about everything, including most
system configurations. To edit these text files, we cover the
two most commonly used text editors under UNIX: vi and
emacs. These editors allow you to create, modify, and view
text files. Vi was hot technology in the 1970s but shows its age
today. Yet, as a new user, youll have more luck with vi.
You can select from many brands of commercial word
processors that provide WYSIWYG what -you see-is-whatyou-get computing, even through this chapter concentrates
on a set of typesetting tools that definitely doesnt provide any
form of WYSIWYG.
You start with original text files created with any text editor,
such as vi or emacs. You then feed these files of troff, or the
related nroff or ditroff. Troff translates dot commands in text
file and output formatted text.
Some of these dot command include .ad to run off text
justification, and .ce which center lines of text. To speed your
work with troff, you can use a set of prebuilt macros, such as
the memoranda macros, or mm. These macro packages include
a number of shorthand macros for the longer troff commands.
104
1.
What is vi?
3.
2.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
Write the command to filter the entire buffer through the sort
-u command.
b)
d)
c)
e)
Chapter 7
MULTITASKING
MULTITASKING
REAL - TIME PROCESSES
USING THE JOB SHELL
SWAPPING AND PAGING
106
Chapter 7 : Multitasking
When you boot a UNIX system, the first process launches a program
called init, which then launches other processes. Init is the mother
of all UNIX processes- or, as referred to in UNIXdom, init is a parent
to other processes, which in turn can act as parents to additional
processes, called child processes. It is, ultimately, the ancestor of all
processes running on the system.
When we describe the shell and its importance in running programs
for you, we were referring to the shell acting as the parent and
managing other child process. Unless you tell it otherwise the shell
waits while you run a child and returns with a prompt after the child
process is finished, or dies. If a child process dies but this fact is not
acknowledge by the parent, the child process becomes a zombie.
Its up to the operating system to keep track of these parents and
children, making sure that processes dont collide. This means
scheduling processes to within a fraction of a second, ensuring that
all processes have access to precious CPU time. Its also up to the
operating system, through the init program, to manage child processes
that have been abandoned by their parents. These abandoned
processes are called orphans.
Through we have mockingly referred to the high level of abstraction
associated with the UNIX operating system, using names like parent,
Chapter 7 : Multitasking
107
$ ps
PID
89
93
95
TTY
p1
p1
p1
TIME
0:01
0:00
0:01
COMMAND
xterm
csh
ps
$ ps -e
To get a full view of the whole of the whole system, you can use:
or
$ ps -ef
$ ps -e1
Depending on the size and number of users on your system, you may
regret using this option.
For our purposes the most important column is the first one, which
lists the IDs of running processes. When the kernel launches a new
process, it assigns an ID number to the process.
$ kill PID
108
Chapter 7 : Multitasking
suicide. Not all processes respond to the straight kill command for
instance, shells ignore a kill command with no options. To kill a shell
or other particularly stubborn processes, use kill with the -9 options.
$ kill -9 PID
$ kill 0
The job shell, jsh, may not be the most frequently used shell, but it
does a credible job at allowing you tight control over multiple jobs.
This is a situation where knowledge of processes is important;
otherwise, the many nifty features of jsh would be lost on you.
For example, jsh allows you to get a decipherable list of current jobs:
$ jobs
[1]
+
[2]
-
Running
Suspended
sort AL_West
>
sort
AL- East>
AL &
AL &
Armed with this information, theres a lot you can do with the job
shell. For instance, you could kill the job with the ever-popular kill
command. However, theres a little difference when using it in the job
shell you must combine the job number with a percentage sign (%) as
in the following command line, which kills job number one:
$ kill %1
Chapter 7 : Multitasking
$ stop %1
109
The neat thing here is that you have the option of starting the
command again in either the foreground or in the background. To
start job number one in the foreground use the following command
line:
$ fg %1
$ bg %1
The mechanism is simple. When you launch a new process, the kernel
attempts to fit the process in an unused portion of RAM. If theres
RAM available the kernel loads the process and begins execution. If
theres not enough RAM available, the kernel looks for a loaded
process thats not running at that particular moment. The process is
then moved to a special area of the hard disk devoted to swaps, and
the new process. The kernel will then swap in the previous running
process if its activated by the user if enough RAM becomes available.
Swapping to and form disk slows down a system tremendously; this
action is called thrashing in UNIXdom, and it serves as a very vivid
metaphor so that you can envision exactly whats happening to your
disk(s). As we said before, a more elegant way of supporting many
users would involve buying enough RAM to allow everyones programs
to be active in RAM simultaneously. Its a waste of a good UNIX system
to be spending most its time accessing the hard disk.
Newer UNIX systems take the notion of swapping a step further with
the implementation of paging, also known as virtual memory.
Paging is very similar conceptually to swapping but increases server
efficiencies that help minimize thrashing on many systems.
If your UNIX system support paging , all memory and programs are
divided into pages, which are equally sized . When you launch a
process, the kernel searches for a page of available RAM, and into
that is loaded the first page of your programs runs, it may need
additional pages for data or execution space, and so the kernal looks
for more free pages. If no paging area on your hard disk. Process are
not grouped contiguously, and one portion of a process may be active
while another portion may be paged out. Because these processes can
be split, this method of using hard-disk space as RAM requires
special hardware support from the CPU.
110
Chapter 7 : Multitasking
Chapter 7 : Multitasking
111
$ ps
$ kill PID
Where PID is the processs IF number, which you can get from
the ps command.
Because UNIX can run more processes than it has RAM for,
UNIX systems usually
support swapping or paging, both
move a process or portions of a process to disk, freeing
memory for other processes. If your system is constantly
paging or swapping, youll soon see what thrashing means as
your system slows to a crawl. To avoid this, you need to run
less processes or buy more RAM.
Chapter 8
ADVANCE NETWORKING
TECHNIQUES
ADVANCE NETWORKING TECHNIQUES
FREE SOFTWARE & FTP
SURFING THE NET
READING & WRITING THE NEWS
THE WORLD WIDE WEB
114
INFORMAL COMMUNICATION
uucp Command
A UUCP Primer
Before you use uucp, youll need to know which machines are
connected to yours. The uuname command does just this :
$ uuname
geisha
spike
khan
kirk
picard
115
Using UUCP
Basically, the uucp command is used to copy files from one machine
to another. At first glance, in this age of Internet and the information
superhighway, you may think that this is incredibly retro technology.
And, conceptually, it is.
Realistically, however, the uucp command has its widest application
in the corporate world, where interconnected computers are very
common. In these situations the corporate systems may not be tied
to the outside world, but only connected to other corporate systems.
In this case the uucp command is a handy way of transferring a file
from your system to the corporate headquarters in Chandigarh.
Theres also one added advantage to the uucp command. All in all, its
a rather secure method of transferring files, when everything is set up
correctly. The uucp command, as well as the UUCP utilities, can
enact very specific guidelines on where files can be uploaded to or
downloaded from .
Lets look at a typical uucp command line.
While this may seem to be an usually long command line, a closer look
will show that its a rather simple one.
The handiest use of TCP/IP is the ftp command, which allows you to
grab files from remote machines, your computer is networked with.
116
USING FTP
$ ftp
ftp >
Youll be presented with the ftp prompt, where you enter special ftp
commands. To get a list of available commands, type a question mark
(?) or help at the prompt:
ftp > ?
or
ftp > help
Result
ascii
binary
bell
bye or quit
Close
cd
delete filename
Deletes filename
computer
on
remote
mput filename
Pwd
117
If you download an ASCII file, you can view it using any editor,
including vi or emacs.
If youve downloaded a compressed binary
file, you will have to uncompress it (and perhaps unarchive it) at the
command line using uncompress, unpack, tar, or gzip. How do you
know which one to use.
If the file still has a suffix of tar after using these commands,
use the tar command to unarchive it:
$ uncompress filename.Z
$ unpack filename.z
$ gunzip filename.gz
UNIX insiders brag of being on the net, but what actually constitutes
the net - Internet or Usenet - depends on the user and their system.
Though the two are linked, there are crucial differences, and more
118
likely than not the braggart is on the usenet, since anyone (essentially)
can get on the Usenet.
Thousands of computers are linked - worldwide - in a loose network
called the Usenet. The Usenet is a public network of linked UNIX and
non-UNIX machines, dedicated to sending information to companies,
schools, universities, the government, research laboratories, and
individuals.
biz
comp
misc
news
rec
sci
soc
talk
Subject
miscellaneous subjects
news about the Usenet
recreational activities
science
social issues
talk
119
relating to UNIX the X-window System, and related topics (electronicmail packages like elm and pine, software like emacs)
Topic
Comp.databases
Comp-Source-Unix
Comp.Unix.questions
Comp.lang.C
Comp, text
Misc.jobs.offered
rec.music-gaffa
sci.space.shuttle
C-language issues
Text.processing issues
Job openings
Although all the news items are text files and in theory could be read
with vi or emacs, there are so many of them in so many separate files
that its not really feasible to read each file. A full Usenet newsfeed,
that is, all of the incoming message files from all the worldwide
newsgroups, adds more than 40 megabytes of files to your disk each
day. Thats how a type of software, called newsreaders, evolved.
These newsreaders help you sort out, with varying degrees of
usefulness, what to read from the hundreds of new files that appear
daily. The basic idea is to read those messages youre interested in
and skip the rest. Theres simply no way to read every incoming
message, even if you spent all day in front of your computer.
We are not going to cover any of the many news readers in depth: each
system, it seems, features its own news reader. We find that the most
popular programs are:
120
$ gopher
or
$ xgopher
Much of the buzz surrounding the Internet can be traced to the World
Wide Web and the tools for accessing it - Mosaic, Netscape, and their
ilk.
And, quite honestly, the hype is justified. At its best, the World Wide
Web is an incredibly, efficient and exciting way of distributing
information. The potential of the web has been barely scratched, and
when all is said and done the web will profoundly alter publishing as
we know it.
PAGE LIMITS
It s best to look at the World Wide Web not as a computer service, but
rather as a publishing medium.
At its core, the World Wide Web is actually an ingeniously simple
beast. A web browser, such as Mosaic or Netscape, sends a request
over the network to a web server; the request can be one of five
formats. The Server then honours the request by sending a text file
formatted in the Hyper Text Markup Language (HTML), which inserts
121
tags in the text. The text file is then rendered by the local web
browser, which matches the tags to resources on the local machinefor instance, a tag for TITLE would be rendered in a font and point size
set up through the web browser.
To access the World Wide Web, youll need a web browser. The most
famous web browser is Mosaic, originally from the National Center
for Supercomputer Applications (NCSA) at the University of Illinois.
That isnt to say that mosaic isnt the best web browser on the market,
There are a host of competitors in the UNIX/X-window world, including:
122
Chapter 9
ADVANCE UNIX
COMMANDS
Awk command
Perl command
A First Perl Script
Sed command
At command
Batch Command
Cron Command
Bc Command
BACKING UP YOUR SYSTEM
124
awk Command
Rashmi
Ambica
Smedia
Sanjeev
286
280
279
284
555-6674
555-4221
555-1112
555-2121
ra
amb
10
smedia 2
spike 12
Lets sink into the trap of abstraction for a minute and compare our
example file output to a two-dimensional graph. Each row across is
called a record, which in turn is made up of vertical fields or columns,
almost like a database. Awk allows us to manipulate the data in the
file by either row of column, which makes it more powerful and useful
than the tools discussed earlier.
Using the Awk command is not a complicated process. The structure
of the awk command looks like this.
The only options available with awk are -F, which allows you to
specify a field separator other than the default of white space, and f, which allows you to specify a filename full of awk commands
instead of placing a complex pattern and action on the UNIX command
line.
The simplest awk program merely print out all lines in the file,
280
279
284
555-4221
555-1112
555-2121
ra
125
amb
10
smedia 2
spike 12
Continue our previous example, lets say we wanted to pull all records
that began with the string Ambica. Wed use the following :
$1: Tell awk to use the first column for the basis of further
action. Awk will perform some section on a file based on either
records or fields; a number beginning with a awk to work on
a specific field. In this case $1 refers to the first field.
~ : Tell awk to match the following string.
print $0:
Tell awk to print out the entire record
containing the marched string. A specially use of the
$ sign is with the character 0, which tells awk to use
all of the fields possible.
Ambica 280
555-4221
amb
10
Less than
Usage
<=
$1 <= Rashmi
!=
Not equals
>=
Greater than
>
Greater than
==
Equals
equal to
$1 >= Sanjeev.
$1 > Sanjeev
126
||
For example, lets say we wanted to know how many had a value in the
fifth field that is greater than or equal to 10:
amb
spike
10
12
We can also combine tests, to print out, for example, all workers who
have the fifth field less than 10 and the second field greater than 280:
While these examples are obviously contrived, you can use awk to
help pull out all entries that share certain postal (ZIP) codes, or all
employees who have a salary in a certain range. Were just scratching
the surface with awk.
Awk can also be used to return entire sections of data, as long as you
can specify patterns that begin and end the section. To return the
records of Rashmi and Smedia and all between use the following:
279
555-1112
smedia 2
If we dont want to print the whole record, we can print just a few of
the fields, as in the example below, which prints out field2 and 1:
As with other UNIX commands, awk can be used in pipes, and its
output can be directed to other files or directly to the printer. For
example, if we were looking through a large file and expending many
matches to a particular string , We might want to direct that output
to a file or to a printer. For example to use awk with the UNIX sort
utility, we can sort the output of the last example:
280
286
Ambica
Rashmi
127
perl Command
When approaching perl, the first question to ask is : Do you have perl
on your systems? Many UNIX systems, such as Linux, come with perl
built in. To check this out, simply type in :
$ perl -v
perl: command not found.
See the section on acquiring perl, below, for more on getting perl if
you dont already have it.
#! /user/bin/perl
# My first perl script.
print This is my first perl script. \n:
print oh, joy!\n:
When you run this script, youll see the following output, as youd
expert:
#! /user/bin/per1
# Prompting for input in perl.
128
chop($last_name);
print Your name is $first_name $last_name. \n;
When you run this script, youll see the following prompts:
From the above example, youll note that perl seems more difficult
than the Bourne shell for getting input from users.
sed Command
The sed command can be likened to the text editors vi, emacs, and ed.
However, the vi, emacs & ed. Sed can be thought of as a filtering text
editor; procedurally, you use the sed command with the following
steps:
These procedures are specified all in one command line. A typical sed
command line should look something like this:
Result
-f
-e
-n
129
Lets begin by using sed display only a portion of the file test, like the
second and third lines. Do so with:
Result
c\string
a\string
d
i
l
I n s er ts sp ec if ie d s tr in g b ef or e
specified lines.
130
p
r filename
s/string1/string2
w filename
at Command
$ at llam
After you hit the Enter key youll be placed on the following line,
without a prompt. As you recall, this is the UNIX method of asking you
for additional input. This is where you provide the command that at
is to execute; end each command by hitting the Enter key. When
youre through type Ctrl-D.
batch Command
$ batch
End the command by hitting the Enter key. As with at youll be placed
on a new line, as batch waits for additional input. Go ahead and type
in the commands, ending each by hitting the Enter key. When youre
finishing entering commands, type Ctrl-D.
131
cron Command
bc Command
$ bc
l + l
2
quit
This simple equation shows how to use bc: Type it as a command line,
hit Enter, enter your equation, hit Enter, read the calculation and
type quit when youre through. Obviously, other more advanced
features are available, such as square roots, converting numbers
from one base to another, determining prime factors, control
statements for writing programs, and more.
tar Command
We advice that you back up your work often - as possible. There isnt
a computer user anywhere who hasnt accidentally erased an important
file at one time or another. In many ways, the regular and systematic
132
Lets say you wanted to back up all the files in an important directory
- /usr/erc/data/reports - to make sure that you dont lose any of
your work to date. Before using tar, make sure that your current
directory is /usr/erc/data/reports:
# cd /user/erc/data/reports
v
.
If, for example, we wanted to back up only those file ending with c; we
could invoke a wildcard:
The above command stores all of the files ending with c into the tar
archive file named archive.fil. In this case archive.fil is just a
standard UNIX file. Since UNIX treats hardware devices as files, we
can back up our files to a tape, by replacing the file name archive.fil
with the name for the tape device, usually /dev/tape.
To restore files from the archive, use tar as in the following :
133
The previous command extracts (the -x option) the files stored in the
tar archive file and places these extracted files into your current
directory. The -f option is followed by the name of the tar archive file.
And the -v option again sets tar into verbose mode, providing
important status information. The following table lists more tar
command :
Command
Result
c
t
u
w
x
Tar is not the only backup tool available in UNIX, though we find it
the most widely used. Another backup tool is cpio, which has been
called the most difficult to use UNIX command by users.
134
Chapter 10
THE X-WINDOW
GOING GRAPHICAL - THE X WINDOW SYSTEM
WINDOW FOCUS
136
The X Window system - even the concept - confuses most new users.
Is it a UNIX shell? No. Is it the all-singing, all-dancing graphical
system that will cure all your computing woes? Not yet. Is it a
standard? Yes, although some vendors - most notably workstation
giant Sun Microsystems - have been brought into the X fold kicking
and screaming. Is it a workable business-oriented environment? Yes,
but just barely.
Just about every modern UNIX software package, form the xmahjongg
game to the WYSIWYG (what-you-see-is-what-you-get), Asterisk word
processor, runs under a graphical interface. Unlike the cryptic dot
command introduced for troff, Asterix provides a friendly menudriven graphical interface, as does Island Write, FrameMaker, and
almost every other X-base package. All of these programs run on top
of the X Window System.
Flexibility
Protability
137
Network transparency
If youre using UNIX (which we assume you are, or you wouldnt have
read this far) and run a graphical windowing system. Well youre
running X. Very few non-X graphical UNIX system survive today.
Thus if you want to learn how to get the, most out of your system, then
it is good for you to learn X.
THE X SERVER
138
USING X
139
Starting X
Before you can run any X application, through , you need to start the
X server. The X server takes control of a display; the keyboard, a
pointing device (usually a mouse), and at least one video monitor sometimes more in multiheaded systems.
An X server alone isnt worth much - all you get is a crosshatch
pattern and an X cursor. Youll also want to start a number of X
applications, including a window manager, when you start up the X
server. The applications are important; the X server merely provides
the infrastructure.
$ xinit
140
Obviously youll choose a program that you intend to keep around for
your entire X session. Like the pervious example, most users end
their .xinitrc file by running a window manager, such as twm.
There are two main reasons for this. First, you want a window
manager running during your entire X session. Second , most window
managers provide a menu choice that allows you to exit. This menu
choice is an easier (and easier to remember) way to quit X than typing
Ctrl-D in an xterm window, or using kill to terminate the X server.
Using the previous example, exiting the window manager also exits X.
Whatever program you choose, this last key place holder process
controls when X exits. When this process exits, X does too.
If xinit fails to find a .xinitrc file, it merely starts the X server and
one 25-line xterm window.
USING STARTX
Lets go over our example .xinitrc file line by line. The .xterm
command starts an .xterm window:
Since most computer users are Type A personalities, they all want to
know what time it is - all the time. There are two main X clock .xclock
141
$ exec twm
Meaning
-bd color
-background color
-bg color
-bordercolor color
-borderwidth border_width
-bw border_width
-display display_name
-fg color
-fn fontname
-font fontname
-foreground color
- geometry gemetryspec
- gemo geometryspec
-iconic
-reverse
-name name
-rv
142
-tittle tittle
-xnllanguagelanguage[terr][.code] S e t s
language,
and
optionally territory and
codest for current locale.
-xrm resource_command
Using the mouse to move around the screen real estate isnt a big
deal, particularly if youve already done some work on a computer
running Microsoft Windows ,OS/2, or the Macintosh operating system
. However if youre unused to working in a graphical environment with
a mouse, there are a few things youll need to master before you
become completely at ease.
X allows you to perform many distinct acts with the mouse-probably
more than you thought possible. Roughly speaking, X mouse actions
can be divided into four groups:
143
As you play with the mouse and the pointer , youll notice that not
every window is always the same color on the screen, and that at
times a window wont be able to accept your input.
In X, windows are said to have focus (or sometimes input focus),
which is a fancy way of stating that you can type into or manipulate
a window. Only one fancy window at a time can have focus. Depending
on the window manager in use, X does tell you which window has the
focus; in most instances the window that has the distinctive color (or,
actually, the only color) is the window with focus.
With most window managers, you need to explicitly set the focus by
moving the pointer over a window and clicking on the left mouse
button. If you click on a window thats partially obscured by another
window, giving it the focus will move the obscured window on top of
the previously obscuring window. (This sound much more complicated
than it really is. Trust us.) Dont worry if you have a window partially
obscuring another; the obscured window is still fully functional and
running a program.
One problem that way plague your system is not being able to find the
X programs in your command path. If you get a command not found
error when you run any X command, this is probably the case.
Despite all the fuss over the X Window Systems value as a graphical
user interface for UNIX we find the most frequently used X program
to be xterm.
144
After all is said and done, most users still need to enter UNIX
commands at a command shell prompt, mainly because X-tools
simply arent advanced enough to completely hide the command
prompt and obsolete the shells. Luckily, were already well-versed on
the UNIX shells. xterm manager the interface to X so that all of your
old text-based program, like the vi text editor or the elm electronic
mailer, as well as UNIX command work just fine inside xterm.
It seems odd to use a graphical windowing system merely for commandline windows, but xterm provides more than a simple command line.
You can control xterms window size and location, fonts (and
font size), as well as the foreground and background colors.)
You can have multiple xterm window on screen at the same
time - and copy and paste between them. They can overlap or
sit side-by - side.
STARTING XTERM
You can start an xterm window (normally for another xterm) with the
following command
$ xterm &
This will start the xterm in the background. You must be running the
X sever the X-sever for this to work. Normally, youll start the xterm
in the background, so that you can continue to work in our current
terminal. You may want to arrange your X start-up configuration to
launch more than one xterm Window - all in the background, by
editing your .xinitrc file.
Setting X Fonts
Like most X application xterm will accept a font name command line
parameter Use either - font font name or - fn font name
Chapter 11
INTRODUCTION TO LINUX
LINUX- THE NEW GENERATION OPERATING SYSTEM
HISTORY OF LINUX
HOW IS LINUX DIFFERENT?
LINUX V/S OTHER OPERATING SYSTEMS
WHAT IS INCLUDED WITH LINUX?
WHO USES LINUX?
INSTALLING LINUX
146
NEW FEATURES
147
The short technical explanation is that Linux is a multi-user, multitasking operating system that runs on many platforms, including
Intel processors, 386 and higher. It implements a superset of the
POSIX standard. Linux inter-operates well with other operating
systems, including those from Apple, Microsoft, and Novell.
This complete operating environment includes:
148
make their installation software proprietary and sell the package with
support for a nominal fee.
This doesnt mean there is nothing left to buy or wish for, but it does
mean that if, for example, you are a software developer, theres not
much you need to buy in order to turn Linux into a reasonably
effective development platform.
One of the more common things people want to do is connect to the
Internet. Everything you need to connect to the Net is available for
Linux for free. In fact, Linux can be turned into a first class Web
server with a software available for free.
Unix is compatible with Linux at the system call level, meaning most
programs written for either Unix or Linux can be recompiled to run on
the other system, with little or no modifications. While traditional
Unix runs on more types of hardware than Linux, it has paid the price
of over 25 years of baggage to make this possible. That means Linux
will run faster than Unix on the same hardware. Moreover, Unix has
the disadvantage of not being free.
MS-DOS, like Linux, has a hierarchical file system. But it only runs
on x86-based processors, does not support multiple users or multitasking, and it is not free. Also its interoperatility with other operating
systems is poor and it does not include networking software,
development programs, or many of the utility programs included with
Linux.
Microsoft Windows offers some of the graphics capabilities of Linux
and includes some networking capabilities, but it suffers all other
handicaps of MS-DOS.
Windows NT is available for the Digital Alpha, as well as x86 processors,
but it suffers many of the disadvantages of Windows. It has had much
less time in the field (meaning less time to work out bugs), and it has
a rather large price tag attached to it.
Apples operating system for the Macintosh runs only on the Mac. It
also suffers from a lack of development tools and less-than-smooth
interoperability with other systems.
When you get Linux, you get everything. That is, everything you would
expect to be included with an operating system, and more. Each
149
For example, Linux can be used by a small ISP. To offer this sort of
service you need:
Internet connectivity
Online backups
Most of these capabilities are inherent in Linux. The others come with
the hardware needed to support the capability.
PPP and SLIP are integral parts of Linux. Their support and the
number of channels supported are configuration options when you
build the Linux kernel. Support for regular Unix login/password
security is also available.
Usenet news and Internet mail are also included. The software to
support news includes the standard systems available on Unix
platforms. INN seems to be the most popular. Mail is handled by
sendmail for most systems. While not as capable, smail is also
available and may be a better fit for low-end configurations.
Various Web servers are also included with Linux. Finally, backups.
In order to be a respected ISP you need to offer continuous service and
you cant lose your customers data. After all, thats why they pay you.
Linux includes the standard Unix utilities to do backups (tar, cpio,
and backup/restore). There are also commercial products offering
additional capabilities.
This doesnt mean Linux comes with every application you need to
run your office or your entire business. However, while it may not be
included, it may be available. For example, databases, word processors,
spreadsheets, and sophisticated graphics programs are available for
Linux. You will see names like Applixware, Corel, and Empress in
the Linux camp when you look for these sorts of applications.
150
Linux doesnt need the latest, fastest, hardware to run on. Hardware
that you brought last year or may be the year before, and are now in
the process of replacing can happily run Linux. Your ancient 386 and
486 can become routers on your network. The Pentium 100 that you
are about to junk could perhaps become your mail server. Moreover
another biggest thing about Linux is that it almost installs by itself.
A full install of Red Hat Linux 6.x will take about 540 MB
but if you are short on disk space, you can also get away with
around 100 MB.
151
For installing Linux only, you should have at least a 1.2 GB hard disk.
For installing it with a dual-boot option, the size depends upon the
space requirements of the other operating system. For instance, if
you want only DOS for the second partition, you dont need more than
100 MB of space.
You will be asked if you are using a color monitor. Even if you have
a monochrome monitor, select yes because Linux will run in greyscale
mode. This is followed by a screen asking you to specify the keyboard
type (select default), and the type of media that contains the packages
to be installed (selectCD-ROM).
You are then asked to specify whether youre upgrading or doing a
fresh install. Choose the latter. The next prompt is an important one.
It asks whether you have any SCSI adapters? If you have a SCSI
bootable device, then you will need the Linux supplement disk. If you
have an Iomega Zip drive installed, Linux recognizes it as a SCSI
device. Dont connect the zip drive now. You can always set it up later
after the installation.
152
DISK PARTITIONING
The next part deals with disk partitioning, and is slightly tricky. You
have to select a partitioning utility to set up the mount points.
Choices available are Disk Druid and Linux fdisk. Both work fine, but
we used Disk Druid. Whatever be the number of partitions you create,
youll always need to create a Linux swap partition and a Linux native
partition. All partitions are created by using the add button in Disk
Druid. Keep your swap partition to 64 MB if you have 16, 32, or 64
MB of RAM. Use the tab key to navigate through the various buttons
in Disk Druid utility.
After creating the Linux swap partition, note down the remaining
hard disk size. The size specified here is 1 MB more than the actual.
When you add partitions, you will be prompted to enter the partition
size. Whatever be the number of partitions, ensure that the total disk
space that you specify is 1 MB less than what Disk Druid displays.
Press the F12 key to save changes and continue. You will be prompted
to select the mount point. This is where all the Linux boot files will be
located (Linux native partition). If it doesnt prompt you for it, then
highlight the Linux native partition and select the edit button in Disk
Druid. Enter a / when it asks you to specify the mount point and
continue.
The next two options prompt you to format the swap space and the
Linux native partition. Both screens have an option to check for bad
blocks while formatting. If you have a new hard disk, you can disable
this option, as checking for bad blocks takes time. If you have an
older hard disk, and are not sure whether it has bad blocks or not,
you should enable this option. Also, note that at this point, you can
switch between screens showing the log file, or the Linux shell prompt
by pressing Alt+F1, F2, and F3. These can be useful if something goes
wrong with the installation, and youd like to check the log file for
errors, or to go to the Linux shell prompt to check for installed
directories.
After all the files are copied, Linux will detect your mouse, display
adapter, and the monitor. In each case, it displays a list of devices to
choose from. Select from the list of devices that pop up. If youre not
sure of which mouse and monitor you have, select Microsoft compatible
mouse, and generic monitor options. When it asks you to set up the
default resolution and color depth settings, select dont probe (selecting
153
probe may halt your system). You will also be prompted to enter the
video memory and the clockchip present in the display. Enter the
video memory, and leave the clockchip setting to no clockchip. Next
enter the mode you want to run it in. This is where you enter the
resolution and color depth. Choose the one your display adapter
supports. All these settings are required to run X Windows. If these
settings are not correct, you can always reconfigure them after the
installation. For this, login and type Xconfigurator (X should be
capital). Same prompts for setting your display card and monitor will
come up again.
CONFIGURING LINUX
You have now completed the basic installation of Linux. Next comes
th e configur ation p art. Fir st on the agen da is the n e twor k
configuration. Linux automatically detects any network cards in your
machine. If theres a PCI Ethernet card, Linux automatically detects
it and continues to the TCP/IP configuration. But if theres an ISA
card, you will need to supply a base address to it before proceeding.
Commonly used base address is Ox300. In the TCP/IP configuration,
you have to specify the IP address, netmask, default gateway, and the
primary nameserver. If you are setting up a fresh network, then use
the reserved IP address range meant for LANs192.168.1.x. It makes
sense to give this machine the IP address 192.168.1.1. If this is also
your primary gateway to the Internet, then set the Gateway address
to the same IP address.
Then you are prompted to enter the domain name, and the host name.
If you have a domain name registered, you can enter that here. For
example, we used cmil.com as the domain name, and <computer
name>.cmil.com for the host name.
There are only a few more steps left. You have to configure the time
zone. Choose Asia/Calcutta from the list as that is the only one
available for the Indian subcontinent. Linux then prompts you to
start the services, and gives you a list of the ones its going to start.
Leave it to default and continue.
Appendix A
THE BOURNE SHELL
THE BOURNE SHELL
PRECEDING A COMMAND BY ITS PATH
COMBINING COMMANDS
SHELL VARIABLES
156
Appendix - A
This chapter introduces the agency that sits between the user and
the UNIX system. It is called the shell. All the wonderful things that
you can do with UNIX are possible because this agency can
understand so much by seeing so little code. It is more like an
efficient secretary who understands your directives from your gestures,
and carries them out by specially devised means which you neednt
know. Like the command processors of other operating systems, the
shell process the instruction that you issue to the machine. But the
shell is much more than a command processor, and a through
understanding of its features is necessary if you are to exploit the
power that UNIX offers.
The Bourne shell, named after its founder steve Bourne. It is one of
the earliest shells that came with the UNIX system, and also one that
is most widely used. There are other shells that feature in every UNIX
system today. Notable among them are the C shell, a product from
the University of California. Berkeley and the Korn shell from David
Korm of Bell Laboratories. The C shell has an advanced user
interface with enhanced features. The Kom shell is the most modern
shell available, and is likely to become the industry standard.
If you list out the /bin directory (/usr/bin in Release 4), you will see
an executable program named sh. This is the Bourne shell. The C
shell and the Korn shell, if present will have the names csh and ksh,
respectively. The shell is the sleeping beauty of the system, even
though it acts as your interpreter when you try to talk to the machine.
When you issue an instruction, i.e. command, the shell is the first
agency to acquire the information. Before executing the command,
it sees whether the command line is in a form which the system can
understand. If it is not , then it processes the request to recreate a
simplified command line. It then leaves the job of command execution
to the kernel.
The shell is really a UNIX command a program that starts when you
log in, and terminates when you log out. But unlike other UNIX
commands, it is there all the time, indicating its presence by the
familiar $ prompt. This point has to be taken seriously because the
shell program starts executing the moment a user logs in. It
resembles the role played by COMMAND. COM in MSDOS, through
the capabilities of the shell far outweigh those of COMMAND.COM.
The unique thing about the shell is that, while it is technically a UNIX
command itself, its main job is to accept and interpret user requests,
i.e. other UNIX command.
One of the functions of the shell is to wait for input from the user.
Anything keyed in through the keyboard, and at the $ prompt, is
Appendix - A
157
(a)
(c)
(b)
(d)
When there is no input from the user, the shell is said to be sleeping.
This is indicates by the $ prompt, meaning that you are now free to
enter any text. It wakes up whenever a user enters some characters
through the keyboard , and presses the <Enter> key (sleeping,
waiting and waking are accepted terms in UNIX parlance). The
productive work of the shell begins after it has accepted the
characters that are keyed in.
So what does the shell do with this input ? It first scans the command
line, and processes it in a number of steps. During the scanning
operation, it looks for certain characters which have a special meaning
for it. Because it permits abbreviated command lines (like the use of
* to indicate all files, as in rm*), the shell has to make sure the
abbreviations are expanded before the command can act upon them.
This is important because these special characters usually mean
nothing to the command. It rebuilds the command line at every step,
and when all processing is complete, it passes on the processed
command line to the kernel for execution.
$ /bin/date
You normally dont need to do that for files residing in the /bin and
the /usr/bin directories, but if you are to execute programs residing
in some other directory which is not current directory, then the
pathname must be specified.
158
Appendix - A
In one shot, you can assign read and write permissions to the file
note, and then see with the Is command whether the action has been
performed. You can combine a number of such commands in this
way, using the : to separate. If the sequence of characters continues
beyond the width of the terminal, you can comfortably continue
entering the input without hitting the <Enter> kry. All you will be
seeing is that the line has been carried over to the next, but that wont
affect the performance in any way.
$ x = 37
$ echo $x
37
$
All shell variables take o the generalized form variable = value. They
are of the string type, which means that the value is stored in ASCII
rather than binary format. When the shell reads the command line,
it interprets any word preceded by a $ as a variable, and replaces the
word by the value of the variable. There must not be any spaces on
either side of the = operator, because the shell treats spaces as the
delimiter of arguments. You cant assign multiword strings to a
variable in this way :
Appendix - A
159
The first word is assigned to the variable msg, and then the shell has
attempted to execute the second word. The shell has a feature of
making an assignment before the execution of a command in the
same command line, which you will see later, have is obviously not a
command, so the shell responds accordingly. To assign multi-word
strings to a variable, you should quote the value :
$ msg=You\have\mail
$ echo $ msg
You have mail
$
$ pn=/usr/kumar/progs/data
$ echo $pn
/usr/kumar/progs/data
$ cd $pn
$ pwd
/usr/kumar/progs/data
$
$ files=unit01 unit02
$
160
$ wc $ files
436
892
1328
$
Appendix - A
6463 37986
8273 48420
14736 86406
unit01
unit02
total
A shell variable can be used to replace even the command itself. You
can assign the above command itself to a variable count . When a
command is assigned to a variable, the variable should be evaluated
(i.e. the command executed) by simply specifying the $-prefixed
variable as the only word in the command line:
$ count=wc $ files
$ $count
436
6463 37986
892
8273 48420
1328
14736 86406
$
unit01
unit02
total
Appendix B
ENVIRONMENT IN UNIX
LEARNING ABOUT YOUR ENVIRONMENT
SHELLS & YOUR ENVIRONMENT
162
Appendix - B
When you login your UNIX system, youre immediately thrust into
your login shell. We discussed logging in your system and setting up
a password, we were detailing how you were configuring your login
shell. This information is usually contained in the file /etc/passed,
as is login information for all the users on your systems. This file is
organized by user, with each line, containing the basic information
regarding every user. name, login ID, and so on. The final field in your
line lists the shell you want to run after logging in. Again, this isnt
terribly important to your daily UNIX usage, but it shows that every
aspect of UNIX usage is governed by a shell of some sort.
Based on this information the UNIX system then launches your shell,
with information contained in the .profile file for C shell users, the
.login and .cshrc files; for Korn shell users the .kshrc file.
As discussed UNIX features several shells, and you have the power to
change shells when you want. As a new UNIX user, one of the most
useful aspects of your shell is its flexibility as exemplified by its
extensive use of variables.
VARIABLES
When you initially login a UNIX system, many of the variables have
been set by the system automatically. However, many others have not
Configuring these variables is up to you:
$ VARIABLEENAME = VARIBLEVALUE
Meaning
DISPLAY
CDPATH
Appendix - B
EDITOR
HOME
163
LOGNAME
MANPATH
PAGER
PATH
PS1
SHELL
TZ
TERM
USER
VISUAL
Before you start messing with your variables, you probably should
know a little about your current variable. To generate a list of your
current shell variables, use the command set:
% setenv
164
CDPATH=:/user/home/:/users/kevin
HOME=/users/kevin
LOGNAME=kevin
MAIL=/users/kevin/mail
Appendix - B
PATH=/usr/bin
SHELL=/usr/bin/sh
TERM = vt 100
TZ = CST6CDT
$ echo $HOME
/users/home
If you want view a specific variable at any time, use the echo
command along with the name of the variable:
$ echo $HOME
/user/home
You arent limited to the variable less define by the system: you could
set up your own variable and refer back to them. This process is called
assigning variables in UNIX parlance.
$ DATA = /users/kevin/data/research/1995stuff
$ ls $DATA
Appendix - B
165
$ export DATA
If youre planning on exporting every variable you assign, you can use
the set command with the -a option to tell the shell to automatically
export every assigned variable.
$ set -a
Removing Variables
After a variable serves its purpose, its a good idea to remove it, using
the unset command. The following command removes the variable
DATA:
$ unset DATA
$ env
EDITOR = vi
ED = vi
HOME = /user/kevin
LOGNAME = kevin
MAIL = /users/kevin/mail
PATH = /usr/bin
PS1 = :
PS2 = ...
SHELL = /usr/bin/sh
TERM = vt100
VISUAL = vi
166
Appendix - B
Hardcore UNIX users lose to fiddle with their systems, which leads to
the 70 or options, available just for terminal configuration alone
when using the stty command.
$stty echo
SPECIFYING AN EDITOR
EDITOR =vi
ED=vi
VISUAL=vi
e.g.
PATH =/user/bin
With PATH defined like this, the shell will not go to any other
directories in search of command. However, the PATH statement may
be the culprit when you issue a command that you know exist and
your system report that accompanying file cant be found. If its a
frequently used command go ahead and add the directory to your
PATH statement making sure that you separate the directories with
a colon:
PATH=/user/bin :/bin
Appendix - B
COMMAND SUBSTITUTIONS
167
$ echo date
date
$ echo date
Set Jul 25 12:27:48 CST 2001
Appendix C
C PROGRAMMING
C PROGRAMMING
WRITING A SMALL C PROGRAM
WORKING WITH CC
170
Appendix - C
Most C programming files use special suffix to tell what type of file
they are, A few of the most common are listed in table below.
File Suffix
DOS Equivalent
Meaning
.h
.h
C include file.
.c
.o
-c
obj
.asm
a.out
.exe
.a
.lib
.C
.cpp
.cpp
.cpp
.cc
.cpp
.cxx
.cpp
.f
.for
.c++
fox
.cpp
.fox
C program
Object module(compiled
from a.c file)
Assembly code.
Library
Fortran program.
Fortan program
Most C programs are stored in one or more files that file end with .C,
like inventory.C and checkin.c for example. When you compile a C
file, the C compiler, cc, creates an object file, usually ending with .o.
The linker ld, then links the .o. file together to make an executable
Appendix - C
171
program. The default name for this program end up with names like
ls,cp, or mv. All of this is controlled by the cc command.
Cc Command
The cc command executes the C compiler, which can compile and link
c programs into executable commands. The myriad of options to cc
controls exactly what the compiler does. We wont cover all of the
many cc options, instead, well introduce the most important ones
and let you read the online manual for cc for the rest, Use the
following command to read the manual pages for cc
$ man cc
Getting a C Compiler
Many modern UNIX systems dont come with the tools you need to
write your own programs. In that case, youve out of luck unless you
ca n som eh ow ac qu ire o ne. F or m a n y o f us s tu ck i n t h e se
circumstances, theres a nice alternative. The Free Sof twa re
Foundation, creators of emacs, also have created a neat-o free C
compiler. This compiler, called gcc, is available over the Internet
form prep.ai.mit.edu and a host of other sites. The GNU C compiler
is available in source-code from, which leaves you with a chickenand-egg problem: You need a C compiler, the cc program, to compiler
the source to this C compiler, So, youll need to get both the binary
version for your hardware platform as well as the source code.
To, test your C compiler, you can enter the following program:
# include <stdio.h>
main ( )
{
/* main */
/* This is a comment */
172
$ vi hell.c
Appendix - C
After you type in this short program, you can follow through the
following simple steps to create a working executable program from
this C file .
The program you typed in was simple a text file. Theres nothing in it
to make it an executable command C program arent like shell scripts
, so we cant simply mark the text file with the execute permission to
make it a working program. Instead, we need to compile and link the
program. Both steps are accomplished by the following cc command:
$ cc .o hello hell.c
The above command runs the C compiler, cc. The -o option tells cc to
build a program named hello. The hello.c part of the command tells
cc to compile the file named hello.c . The cc command both compiled
and linked the program.
Now, you should have an executable program named hello. You can
execute this program by typing hello at the command line. When you
do, youll see the following output.
$ hello
cc -c hello.c
Appendix - C
173
$ ls -l hello*
-rw-r-r- 1 erc
-rw-r-r- 1 erc
users
users
The next step is to link object files (usually theres more than one) into
an executable file. To do this, we again use the -o option to cc, but
this time we pass a .o file at the end of the command line, rather than
the . c file we used above:
cc -o hello hello.o
This command links together the file hello.o into the executable
program hello. You can place more than one object file name on the
command line, as in the following example:
cc - 0
hello
Were not trying to torture you. You need to know how cc operates to
compile a large amount of the freeware youll find.
174
Appendix - C
-l directory
-c filename.c
-o program
-g
-O
Meaning
Appendix D
UNIX COMMANDS
SOME BASIC UNIX COMMAND
176
Appendix - D
alias
Description
Syntax
at
alias namecmd
alias nameemd
Description
Syntax
(ksh)
Options
-l
time
-r
Description
Syntax
at time
Note-
banner
Appendix - D
bg
cal
Description
Description
Syntax
Syntax
Syntax
cancel ID
cancel printer
Description
Syntax
Options
-u
-v
Description
Syntax
Options
-c filename
-g
-o filename
-O
cd
cal
cal year
Description
cc
bg PID
cancel
cat
177
-l library
Description
Syntax
chgrp
Description
Syntax
178
Appendix - D
chmod
Description
100
200
040
020
010
004
002
001
chown
Description
Syntax
Options
cp
Syntax
compress
Meaning
-h
Description
Description
Syntax
Syntax
Option
-r
Description
Syntax
-i
-p
crontab
compress filename
Appendix - D
csh
Description
Syntax
date
Description
Syntax
Options
179
Starts the C shell.
csh
mmddHHMMMMYY
diff
Description
Syntax
Options
-e
Description
Syntax
Options
du options filename
-a
-s
-r
echo
-b
-c
du
Description
Syntax
env
Description
Syntax
Options
ENV=VALUE
Description
exit
180
file
Appendix - D
Description
Syntax
find
Description
Syntax
Options
grep
Description
Syntax
Options
-l
-v
Description
Syntax
options
-n
Description
Syntax
Ignores case.
jobs
Description
syntax
kill
In
Finds a file.
-n
history
file filename
-c
-i
head
Description
Description
syntax
Syntax
Options
-s
kill process.id
In filename1 filename2
Appendix - D
Ip
Description
Syntax
Options
lp filename
-m
Ipstat
Description
Syntax
Options
-d
Description
Syntax
Options
-a
-l
-d
-m
-q
-r
-t
make
-c
-d
Is
181
-1
Description
Syntax
Options
-f makefile
182
-n
-s
man
Description
Syntax
mkdir
Description
Syntax
Options
more
-m mode
Description
Syntax
Options
mv
-c
Description
Syntax
Appendix - D
Options
-f
-i
news
Description
Syntax
mv filename newfilename
Moves file without checking for confirmation in
case of an overwrite.
Prompt users if a action would overwrite an existing
file.
Options
news newsitem
-a
-s
-n
Appendix - D
nice
Description
Syntax
-n
nohup
Description
Syntax
page or pg
Description
Syntax
Options
+n
pr
+/string
Description
password
Description
Syntax
Syntax
Options
passed user
pr filename | lp
-d
-l
-h text
ps
Options
passed
183
-w
Description
Syntax
Options
-e
-f
184
Appendix - D
pwd
rcp
Description
Description
Syntax
Syntax
resume
Description
Syntax
rlogin
Description
Syntax
Options
rm
-l username
Description
Removes files
Options
-f
rmdir
set
pwd
-i
Description
Removes a director.
Description
Syntax
Syntax
rmdir directory
set
setnv
Description
Syntax
spell
Description
Syntax
Options
-b
+s filename
Appendix - D
Stop
Description
Syntax
stty
Description
Syntax
Options
tabs
-a
Description
Syntax
Options
185
Suspends a currently running process.
stop PID
tail
-n
Description
Syntax
Options
-n
tar
Description
Syntax
Options
telnet
Description
Syntax
uncompress
Description
unset
Description
Syntax
186
Appendix - D
unsetnv
Description
wc
Syntax
usetnv variablename
Description
Syntax
Options
-w
Syntax
Options
ami
Description
Syntax
wc options filename
Description
write
-c
-l
who
Appendix E
GLOSSARY
188
absolute
pathname
address
Appendix - E
aging
alias
anonymous ftp
append
application
argument
ASII[American
standard Code
for Information
Interchange]
at
awk
BSD[Berkeley
software
Distribution]
background
backup
Appendix - E
189
bangpath
batch
batch
processing
bc
bin
binary file
bitmap
boot
Bourne shell
buffer
bug
C++
190
general computing
programmers.
world
and
Appendix - E
among
UNIX
C shell
CPU[Central
processing
Unit]
cal
cat
cd
child process
Chmod
Client
command
Command
History
Command line
See history.
Command
mode
Command
substitution
Comments
Communications
node name
Appendix - E
191
Compiler
Compressed
file
Conditional
execution
Console
Core dump
cp
cpio
cron
crontab
csh
Current
directory
Cursor
DOS[Disk
operating
System]
daemon
database
management
192
Appendix - E
date
debugger
default
delimiter
destination
dev
device
device file
device
independent
directory
display
distributed file
system
distributed
processing
ditroff
Documenters
Workbench
Appendix - E
193
domain
domain
addressing
dot command
echo
ed
edit buffer
editor
editing mode
electronic mail
emacs
encryption
end-of-file(EOF)
character
environment
environment
file
environment
variable
194
Appendix - E
eqn
D o t c o m m a n d s us e d t o t y p e s e t e q u a t i o n s i n
conjunction with troff.
error message
escape key
etc
executable file
execute
permission
exit
export
extension
field
file
file sharing
file system
filename
Appendix - E
195
filling
filter
find
finger
foreground
fork
ftp
full pathname
function key
gateways
global
graphical user
interface
graphical
windowing
system
196
Appendix - E
grep
group
head
header
header file
hidden file
hierarchical
file system
history
history
substitution
home directory
hostname
icon
inbox
The storage area for electronic mail that has not been
read.
init
inode
Appendix - E
197
input mode
interactive
Internet
Internet
address
job
job control
job shell
kernel
keyboard
kill
kill buffer
Korn shell
language
library
line editor
198
Appendix - E
link
ln
local area
network
login
login name
login shell
logname
logoff
loop
lp
lpstat
ls
macros
mailbox
make
man
man pages
Appendix - E
199
manual macros
memorandum
macros(mm)
mesg
Meta key
more
Motif
mount
multiprocessing
multitasking
multiuser
mv
NFS (Network
File System)
networking
newline
news
newsfeed
news readers
newsgroup
200
Appendix - E
nice
noclobber
nroff
online-manual
page
Open look
operating
system
options
ordinary files
orphan
owner
paging
parent process
parsing
partition
passwd
password
path
Appendix - E
201
pathnames
permissions
pipes
pg
Postscript
process
process
identification
number(PID)
profile
program
prompt
ps
pwd
RAM(RAndomAccess
Memory)
RFS (Remote
File System)
read
record
redirection
202
Appendix - E
relational
operator
relative
pathname
rlogin
rm
root directory
root user
see superuser,
screen editor
secondary
prompt
sed
server
sh
shell
shell script
shutdown
signal
sort
SPARCstation
Appendix - E
203
spell
standard error
standard input
and output
state
status line
stty
superuser
swapping
symbolic links
system
administrator
system call
system name
system state
TCP/IP
(Transmission
Control
Protocol/
Internet
Protocol)
tail
204
Appendix - E
talk
tar
tbl
telnet
terminal
test
text editor
text formatting
program
thrashing
tmp
toggle
troff
UUCP (UNIX to
UNIX System
Copy)
UUCP Network
Appendix - E
205
UNIX
Usenet
userid
utility
vi
virtual memory
See paging.
wc
who
wildcards
window
manager
word processor
workstation
write
WYSIWYG
(what-you-seeis-what-youget)
X terminal
X Window
System
206
Appendix - E
p a r t ic ul a r o per a t i n g sy s t e m . B ut i t h a s b e e n
popularized with the UNIX operating system.
XENIX
Older version of
microcomputers.
xterm
zombie