Unix tutorial part 3

Document Sample
Unix tutorial part 3 Powered By Docstoc

    2.   sh: THE COMMAND (chap 7)


       All files in UNIX are ―related‖ to one another. The file system un UNIX is a collection of all
these related files (ordinary, directory and device files) organized in a hierarchical (an inverted
tree) structure. This system has also been adopted by DOS and Windows, and is visually
represented in Figure.

                                                 root (/)d

            bin       dev         etc     home          mnt          stand   tmp         usr

Date cat who                dsk    rdsk         henry         unix                       bin     kumar

                         F0ql18dt         0s0                                        login.sql   progs

                                          The UNIX file system

      The implicit feature in every UNIX file system is that there is a supremo, which serves as
the reference point for all files. This top is called root, and is represented by a /(frontslash). root
is actually a directory file, and it has a number of sub-directories under it. These sub-directories,
in turn, have ore sub-directories and other files under them. For instance, bin and usr are two
directories directly under root, while a second bin and kumar are sub-directories under usr.

        Every file, apart from root, must have a parent, and it should be possible to trace the
ultimate parentage of a file to root. If the ancestry of a file can‘t be traced to root, the file is
simply not part of the file system. This should be easy for you to understand as we all have our
own families with similar grandparent-parent-child relationships. Thus, the usr directory is the
parent of kumar, while root is the parent of usr, and the grandparent of kumar. If you create a
file login.sql under the kumar directory, then kumar will be the parent of this file.

       It is also obvious that, in these parent-child relationships, the parent is always a directory.
usr and kumar are both directories as they are both parents of at least one file or directory.
login.sql is simply an ordinary file; it can‘t have any directory under it.
Q sh: THE COMMAND (chap 7)

        When you login to a UNIX machine, you see a series of messages, followed by the $
prompt. As long as you don‘t enter something through the keyboard, this prompt remains there
with the cursor. You immediately conclude that nothing is happening out there, and the system
is idling. Far form it; a UNIX command is in fact running. This command starts running the
moment you log in, and withers away when you log out. It is the sh command, which you can
locate in /bin. This is the Bourn shell.

        Even though the shell appears not to be doing anything meaningful, it swings into action
the moment you enter something through your keyboard. When you issue a command, the shell
is the first agency to acquire the information. While it is technically a UNIX command itself, its
main job is to accept and interpret user requests, i.e., other UNIX command. It first sees
whether the command line is in a form which its agent, the kernel, can understand. If it is not, it
processes the request to recreate a simplified command line. It then leaves the job of command
execution to the kernel. In short, it acts as your interpreter when you try to talk to the machine.

        Many commands require complex interaction with the hardware, like opening and closing
of files, starting up a tape drive unit, or skipping a page on the printer. The shell doesn‘t interact
with the hardware directly. Instead, it works hand-in-hand with the kernel that communicates
directly with all hardware, and takes care of all the complex processes that go on in any system.
Since the kernel interacts directly with the shell, users can afford to remain transparent to the
complex internal processes that take place between the kernel and hardware. This transparency
is one of the beauties of the UNIX design and philosophy.

        The major time spent by the shell is in waiting for input form the user. Anything keyed in
through the keyboard, and at the $ prompt, is actually input to the sh program. With this input, it
performs a series of processing tasks, interacting with the kernel, when necessary. After the job
is complete, it returns to its waiting role, to start the next ―cycle‖. The following activities are
typically performed by the shell in each cycle:

       It issues the $ prompt, and waits for you to enter a command.
       After a command has been entered, the shell scans the command line for some special
       characters, and then rebuilds the command line after processing is complete.
       The command is then passed on to the kernel for execution, and the shell waits for its
       The $ prompt appears, and the shell waits for you to enter the next command.

       When there is no input form the user, the shell is said to be sleeping. This it 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 term in UNIX parlance.) the productive work of the shell begins after it
has accepted the characters that are keyed in.

       The shell first scans the command line, and processes it in a number of steps. During the
scanning operation, it looks for certain characters that have a special meaning for it. Because it
permits abbreviated command line (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. The shell
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.

       The shell, normally, can‘t do any work while the command is being executed. It has to
wait, and when execution is complete, it return the $ prompt for resuming the next cycle.

         There are three distinct phases in the creation of a process, using three important system
calls - fork(), exec() and wait(). Knowledge of the role they play in process creation can often
help to debug shell scripts. The three phases are discussed below:
           A process in UNIX is created with the fork system call, which creates a copy of the
    process that invokes it. For example, when you enter a command at the prompt, the shell
    first creates a copy of itself. The image is practically identical to the calling process, except
    for a few parameters like the PID l when a process is forked in this way; the child gets a new
    PID. The forking mechanism is responsible for the multiplication of processes in the system.
           The parent then overwrites the image that it has just created with the copy of the
    program that has to be executed. This is done with the exec system call, and the parent is
    said to exec this process. No additional process is created her; the existing program is
    simply replaced (or overlaid) with the new program. This process has the same PID as the
    child that was just forked.
            The parent then executes the wait system call to keep waiting for the child process to
    complete. When the child process has completed execution, it sends a termination signal to
    the parent. The parent is then free to continue with its other functions.
          When the process is forked, it inherits the environment of its parent, i.e., it responds to
    the same signals, has the same group-and user-ids, the same priority, etc. most of the
    environment parameters are also available to the child, though some are not. It is also
    possible for the child process too alter the operating environment it has inherited. However,
    the modified environment is not available to the patent process, and disappears as soon as
    the child dies.


    Multitasking capacity
    Multiuser capacity
    Pattern matching
    Programming facility
    System call & libraries
    Windowing system

1) Multi-user Capacity:

       The resources are shared between all users, like CPU, RAM, H/W, etc. for this purpose,
       the computer break up a unit of time into several segments and each; user is allow
       allocated a segment.
       So, at a time, the machine will be doing the job of a single user when first job gets
       completed, the next job gets started.
       The process goes ;on till the clock has turned full-circle. And first user‘s job is taken once
      Whole process is done by kernel.
      There are several types of terminal used with network.
         1. Dumb terminals:- it is having only keyboard and a display unit. It does not contain
            memory or disk of its own.
         2. Terminal emulsion: - A terminal is having its own microprocessor, hard disk, and
            memory. By attaching it to host we can emulate it to work as dumb terminal. At
            that time, the terminal can not use its own memory.‘
           There are s/w like VTERM & XTALK used as a terminal emulsion s/w.
         3. Dial-in terminals: - The terminal is connected to host through telephone line. For
            the dial-up we need modem.

        C                    C

                  S                      C            M            M           S

        C                    C                    C – CLIENT S – SERVER
                             C                    M – MIDDLEWARE

2) Multitasking Capacity:
      It is capable of carrying out more than one job at the same time,. So it is called
      We can switch jobs between background and foreground. One job is running normally
      while other as a background. CPU manages this facility intelligently. Depending upon the
      priority of jobs, the O.S. allots small time slots to each foreground & background process.
      The DOS is also a multitasking of but when one job is executing, it would stops other job
      to execute. So it is not truly multitasking.
      In multitasking, scheduling is very important.

3) Communication:
      It provides communication between two users of same hardware or inter-network. The
      user can easily change data, programs, and mail through such facility.

4) Security:
      UNIX has three inherent provisions for protecting data.
      By assigning passwords and login names to each individual users.
      At file level there are read write, execute permissions, which decide who can read it,
      modify it or execute it.
      The third option is file encryption. It encodes your file into an unreadable format, so that
      even if anybody succeeds in opening it, secretes are sage. When we want to access
      data, we can decrypt it.

5) Portability:
      It can be adapted to any computer system, because it is designed in C language.

6) Pattern matching:
       The ‗*‘ is not only one character used as a pattern matching. But there are so many
       others. The pattern-matching does not only associate with file names.
       Some tolls also use a special expression called regular expression that is framed with
       characters from this set. When you use a single expression to match a number of similar
       patterns, you can watch tem in one shot.

7) Programming facility:
      It is highly programmable. The UNIX shell programming language has all the necessary
      tools like control structures, loops & variables.

8) System call & libraries:
      As it is created in C, there are so many library functions which are be used with system
      The calls are made by kernel.
      Interaction through system calls represents an efficient means of communication with the

9) Windowing systems:
      It provides an environment that allows multiple windows where for each application-each
      X windows also support networked application. Where process is done on one machine,
      while output is on another.

10) Documentation:
      For each utility of UNIX there are documents available.


The functionality of UNIX can be divided into 3 levels.

   User & application program:
        User interacts with applications of UNIX and uses the different utilities of the task. These
applications speak our language to system.

     Communication between user and kernel can be done by a middleware, called shell.
     It is an interpreter (a mediator) that interprets the command that we give. Then it conveys
     them to kernel, which ultimately executes them.
     If we say kernel is monarch (ruler) then the shell is emissary (representative).
     Shell is also called sleeping beauty of UNIX. The shell is agency which takes care of the
     features of redirection with the > & | symbols.‘
     It has its own programming ability.

      It is the heart of UNIX system. It is a collection of program mostly written in C, that
      directly communicate4 with h/w.
      There is one kernel for every system, which is loaded into system, when the system is
      It manages system resources, allocates time between users and processes, and decides
      process priorities & performs all other tasks that we would not like to bother about.

    The kernel isolates itself form the user programs and these programs are independent of
    h/w they use.
    It is easy to move them across different system so. it is often called operating system.
    Kernel programming is called ―UNIX ― whereas the shell program is in a file called ‗sh‘.
    At a time there may be more than one shell but kernel only one.
    At any instance, UNIX is capable of executing only one program, so there is no need for
    more than one shell.



                              OTHER                        UNIX
                           APPLICATION                   COMMANDS
                            SYSTEM SW

   USER         SHELL                                                     SHELL          USER




                              SHELL                           SHELL

               USER                                                           USER


    All the utilities, applications, directories, data are treated as a file. The directory is a file
    that contains several other files.
    It is having hierarchical structure. The file system begins with a directory called root. The
    root directory is denoted as slash (/).
    Within root there are many directories.
         o Bin
         o Lib
         o Usr
         o Tmp
         o Dev etc.

       The root directory also contains a file called UNIX, which is UNIX kernel itself.
       These directories are known as sub-directories and content of these directories are called

                                         /root(root directory)

               unix   bin     lib      dev     usr     tmp       etc   (Sub directory)

                                        user1 user2              usern   (Sub Directories)

                       (Basic Structure of UNIX file system)
       The main reason behind creation of directories is to keep related files together and
       separate them form other group of related files.

    Dev-All devices related files stored in Dev directory.

    Tmp-All temporary files are stored in tmp directory.

    Bin-Bin directory contains executable commands and files. UNIX commands may be
     either ‘C‘ programs or shell programs. Shell programs are collection of several UNIX

    Lib-It stores library functions provided for programmers. The programs written under
     UNIX make use of these library functions in lib directory.
    Dev-Thee dev directory contains files that control various input /output devices like
     terminal, printers, disk devices. For each device there is a separate file. In UNIX each
     device is treated as file. For example, everything that is displayed on terminal is first
     written to a file associated with terminal.
    Usr- All user directories contained in usr directory. In user directory there are several
     directories. Each associated with a particular user. The system administrator creates
     these directories when he creates accounts of different users.
    Tmp-The tmp directory contains the temporary files created by UNIX or by users. These
     files get automatically deleted when the system is restarted.

         Directory                  Contains

         Bin                        Library functions
         Dev                        Device related files
         Etc                        Binary executed files usually required for system
         Tmp                        Temporary files created by UNIX or users
         Usr                        Home directories of all users
         /usr/bin                   Additional binary executable files

Features of UNIX file system:
    It has a hierarchical file structure.
    Files can grow dynamically.
    Files have access permission.
    All devices are implemented as files.

Q - TCP/IP NETWORK (chap 18)

       In a network, a computer is known as a host, sometimes a node, and every such host
has a hostname. This name is unique throughout the network. Each machine is fitted with a
network interface card that is connected by wire to the corresponding cards in other machines.
All communication between hosts normally takes s place through these network interfaces only.

       Every TCP/IP network has an address that is used by external networks to direct their
messages. Every host in the network has an address as well, and the combination of these two
addresses forms the complete network address of the host. For instance, 192.1688 could be the
address of a network, and a host within the network could have the host address of 45.67. In
that case, represents the complete network address of the host. And if the
network is hooked up to the Internet, it has to be unique throughout the world. When two or
more networks are connected together, and use the TCP/IP protocol for communication, we
have an internet, popularly known as an intranet. Note that an intranet is different from the
Internet, which is the super-network of all networks. A local internet or intranet may easily be
connected to the Internet which also uses the same protocol.

      There are various topologies of connecting machines in a network, and technologies. The
most common ones are Ethernet and the token ring. Figure show these two networks connected
to     other host in the same network by a thick, thin or twisted pair cable.

                          CHAP-10 BASIC FILE ATTRIBUTES


      $ls –l

   The first column shows the type and permissions associated with each file. The first
   character in this column is usually a-, which indicates that the file is an ordinary file. At the
   same position –d shows that the file is directory. We can see series of characters r, w, x,
   and -.
   The second column indicates the number of links associated with the file. This is actually the
   number of filenames maintained by the system of that file.
   The third column shows the owner. The owner has fully authority to tamper with its contents,
   permissions and even ownership.
   The fourth column shows the group ownership.
   The fifth column shows the file size in bytes.
   The sixth, seventh, and eighth column indicates the last modification time of the file.
   The last column shows the file name.

         UNIX has a simple, but elaborate system of assigning permissions to files. It follows a
three-tiered file protection system that determines the access rights that you have for a file.
Each tier represents a category, and consists of a string of rs, ws and xs to represent three
types of permissions.
       r – It indicates read permission. The file can be read by using cat command.
       w- It indicates write permission. The file can be modified even
       x- It indicates execute permission. The file can be executed as a program only.

      E.g. Rwxr-xr--
      We can divide the above permission in three part
      rwx All the permission to owner
      r-x Only read and execute permission by the group
      r-- Only read permission to others.

       It is not feasible to give all permission to all users because then security can not be
achieved. The UNIX by default never allows that, otherwise no sensible user will surrender
security so easily. It is also not possible that none of the permission is given to any user.
       rwxrwxrwx             all permission to all            not possible
       ---------             no permission to anyone          not possible

       UNIX adopts a well-defined protection mechanism by which user can have different
permission for different categories of users. If user does not set the permissions of files
correctly, then disaster will be occurred.


       It is an important default security feature provided by UNIX to change file permission by
owner only. It is used to set three permissions for all three categories of users (owner, group,
others). It takes as its argument an expression, which combines the category, the operation and
the type of permission.

   Syntax: chmod <category> <operation> <permission> <filename(s)>
   Abbreviations used by chmod

Category           Operation                               Permission
u – user           + - assign permission                   r – read permission
g -- group         - - remove permission                   w – write permission
o – others         = - assign absolute permission          x – execute permission
a – all

   E.g. – r w – r - - r - -
      In above example execution permission is given to none of user. To assign execution
permission to user, while other permission remains same

$ chmod u+x <filename>           This indicates the user would have execute permission
$ chmod ugo+x <filename>         This indicates the user, group and others would have execute
$ chmod a+x <filename>           This indicates the user, group and others would have execute
$ chmod +x <filename>            This indicates the user, group and others would have execute
$ chmod a-r <filename>           This indicates the user, group and others would not have read
$ chmod ug-r <filename>          This indicates the user and group would not have read
$ chmod u-x,go+r <filename>      This indicates the user would not have execution permission,
but                              group and others has read permission on the same file. It is a
                                 combination of different permission on a single file.

   Absolute assignment
     It can be done by using = operator. It assigns only those permissions that are specified
along with it, and remove other permissions.

$ chmod u-w, o-wx <filename>     or
$ chmod ugo=r <filename>         or
$ chmod a=r <filename>           or
$ chmod =r <filename>

    Octal notation
There is a short hand notation available for changing the file permissions. The command uses a
numeric argument that describes both the category, as well as the permission. The notations
are as bellow:
       Read permission                    4
       Write permission                   2
       Execute permission                 1
$ chmod 421 <filename>            It says that the owner has read permission, the group has
write                             permission, the others has execute permission
$ chmod 777 <filename>            It says that all has all permission. Because 4+2+1 = 6 so 6
means                             read and write permissions
$ chmod 666 <filename>            Only read and write permissions to all
$ chmod 000 <filename>            No permission to any one.

   Directory Permissions
The permissions of directory differ from the file permissions. It is possible that a file can‘t be
read even though it has read permission, and can be removed even when it is write-protected.
It shows that permission of directory also affects the permissions of files.   (16.7)

                                     CHAP 12 grep FAMILY

It is one of the most useful UNIX filters. It scans a file for the occurrence of a patterns, and
display the selected pattern, the line numbers in which they were found or the filenames where
the pattern occurs. It can also select lines not containing the pattern.

Syntax:         $ grep <option> <pattern> <filenames>

It requires an expression to represent the pattern to be searched from file. It is generally safe to
quote the pattern. It is necessary if the search string consists of more than one word or uses
any of the shell‘s character like *.

E.g.   $ grep ‗pattern‘ <filename>

Options                                   Descriptions
$ grep –c ‗pattern‘ <filenames>           counts no of occurrence of pattern inside the filename
$ grep –n ‗pattern‘ <filenames>           the line no are shown where the pattern is found
$ grep –v ‗pattern‘ <filenames>           it selects all but the lines containing the pattern
$ grep –l ‗pattern‘ <filenames>           it displays only the name of files where a pattern has
been                                      found
$ grep –i ‗pattern‘ <filenames>           it ignores case
$ grep –e ‗pattern1‘ –e ‗pattern2‘ <filenames> it allows to match more than one pattern
$ grep –A <no> ‗pattern‘ <filenames>      it allows to match no of lines after specified <no>
$ grep –B <no> ‗pattern‘ <filenames>      it allows to match no of lines before specified <no>
$ grep –N <no> ‗pattern‘ <filenames>      it controls the number of occurrences. So -N2 would
list two                                  occurrence

   The basic expression Character Sub-set

1) Asterisk operator:                     It refers to immediately preceding character.         G*
                                          $ grep ‗pattern*‘ <filenames>
                                          aggarwal, Agarwal, agrawal          [aA]gg*[ar][ar]wal
2) Dot operator:                          it matches a single character
                                          $ grep ‗pattern.‘ <filenames>
3) A specifying Pattern Boundaries:       A pattern is matched at the beginning with the ^ (caret)
  as                                      the pattern prefix, while the $ (dollar) as the pattern
                                          $ grep ―^pattern‖ <filename>
                                          $ grep ―pattern$‖ <filename>
4) [p q r]:                               Matches a single character p, q or r
5) [c1 – c2]:                             Matches a single character within the ASCII range
                                          represented by c1 and c2
6) [^pqr]:           Matches a single character which is not p, q, r

                                     CHAP 13 PROCESSES
Q kill        COMMAND
        The system often requires communicating the occurrence of an event to a process. This
is done by sending a signal to the process. When the process receives a signal, it may ignore it,
terminate or do something else. If user has a program running longer than the accepted, user
can sends signal to active process with a specific request of termination. It can be done either
by interrupt key or by kill command. It takes PID as its arguments, and terminates the process
with that PID.
Syntax:        $ kill <PID>
E.g.:          $ kill 512 98 45 67
        The & operator will show the PID of the process that is run in the background. If user can
run more than one job in the background, they can all be killed with a single kill command and
by specifying all PIDs. If all these processes has same parent process, then killing of parent
process would directly kill the child processes. User can not kill init process.
        The system variable $! stores the PID of the last background job. When user run more
than one job in the background, this parameter stores the PID of only the last one. The $$
variable stores the PID of last process
        E.g. $ kill $!
    Killing with Signal Numbers:
        The kill command uses the signal number 15 to terminate the process, by default.
    Sometimes a program may ignore the interrupt, and still executing the command. In this
    case, the process can be killed with signal no. 9.
        E.g. $ kill -9 121          It kills process 121 with signal no. 9
               $ kill 0             The 0 signal will kill all processes in system except the login
               $ kill -9 $$         Kills current shell
               $ kill -9 0          kill all processes including the login shell
               $ kill -1 0          kill all processes including the login shell

Q – nice COMMAND
      In UNIX environment, all jobs are executed with equal priority. This is not always
desirable, because high-priority jobs must be completed at the earliest. The nice command
reduces the priority of jobs. It is used with the & operator. More important jobs can then have
greater access to the system resources.

       UNIX provides very sophisticated facilities to schedule a job to be run at specified time of
day, rather than now. It is also useful because the load on any system. It makes sense to
schedule less urgent jobs at a time when the system overheads are low. The at command
takes as its argument the time the job is to be executed. The input to the command has to
come from the standard input
       E.g. $ at 12:30
               <Ctrl -d>
       It means that at 12:30 p.m. today the script will be executes. The job number, the
date and the time of scheduled execution are also shown. This job number is derived from the
number of seconds that have elapsed (onwards) since 1970. The standard output and standard
error of this shell script will be mailed to the user, who can then have a look at this mail. The
output can be redirected to any file even
       $ at 12:30 > abc.lst
       It also offers the key words now, noon, midnight, today and tomorrow, which can be
used in scheduling commands. It accepts the + symbol to act as an operator. Another key
words used are hours, days, weeks, months and years.
      $ at noon
      $ at now + 1 year
      $ 12:00 + 1 day
      $ 9 am Mon
      $ 9 am tomorrow
      The at queue is displayed with the –l option. It shows, for each submitted job, its
number, the schedule and date of executions, as well as day of week. But it does not provide
the name of job.
      $ at –l
      $ at –r <job>           it will removes the specified job

                            CHAP – 15 SHELL PROGRAMMING

        The scope of shell programming often goes beyond the limits of conventional languages.
The shell has a whole set of internal commands that can be stringed together as a language,
with its own variable and its own loops. The external command makes shell programming
powerful. It runs in interpretive mode, i.e. one command at a time. So they run slower. The
shell is often used as an intermediate platform to finally code the program in C.

        When a group of commands has to be executed regularly, they are stored in a file. All
such files are called shell scripts, shell programs, shell procedures. There is no restriction for
the file name extension, but .sh is used universally. We can use Vi editor or using cat
command, we can create shell scripts. The # operator is used for command line arguments.

      Shell procedures accept arguments in another situation, when user specifies them in the
command line itself. It is quite useful for scripts requiring few inputs. It also forms the basis of
developing tools that can be used with redirection and pipelines.

       When arguments are specified with a shell procedure, they are assigned to some
variables called positional parameters. The first argument is read by the shell into the
parameter $1, the second as $2, and so on. User can use more positional parameters in this
way up to $9. They are called shell variables because all variables are evaluated with a $
before the variable name. There are a few other special parameters used by the shell.

       $0                   It contains the name of the program
       $*                   It stores the complete set of positional parameters as a single string.
       $#                   It is set to the number of arguments. It lets user to design scripts
that                        check whether the right number of arguments have been entered.
       $?                   It stores the exit status of the last command. It has the value 0 if the
                            command succeeds, and a non-zero value if fails.
       $!                   PID of last background process
       $@                   same as $* except when enclosed in double quotes.

       $ cat
       >echo ―Program : $0
       The number of arguments specified is $#
       The arguments are $*‖
       grep ―$1‖ D2
       echo –e ―\n Job over‖

       $ director emp1.lst
       program :
       The number of arguments specified is 2
       The arguments are emp1.lst
       1006 | jalpa rathod    | director | sales     | 03/09/03 | 6700
       6521 | sunil makhaulia | director | purchaser | 03/09/03 | 7800

       Job over


       The shell provides two operators to control execution of a command depending on the
success or failure of the previous command. These operators are && and ||. The && operator
delimits two commands; the first command is executed only when the first succeeds. The ||
operator is used to execute the command when the previous command fails.
       $ grep „director‟ emp.lst && echo “Pattern found”
       This would give output ―Pattern found‖, if pattern founded in the file.
       $ grep „director‟ emp.lst || echo “Pattern not found”
       This would give output ―Pattern not found‖, if pattern does not founded in the file.

      It takes two-way decision, depending on the fulfillment of a certain condition. It evaluates
a condition that accompanies its ―command line‖. If the condition is fulfilled, the sequence of
commands following it is executes. Every if must have a corresponding fi.
      Syntax:       if <condition>
                            <Execute commands>
                    elif <condition>
                            <Execute commands>
                            <Execute commands>
      E.g.          $ if grep ―director‖ emp.lst
                    > then echo ―found‖
                    > else echo ―not found‖
                    > fi
       When if is used to evaluate expressions, the test statement is also used to control
command. It uses certain operators to evaluate the condition on its right, and returns either a
true or false exit status. It is then used by if statement for decision making. It does not display
any output but simply returns value. There are certain relational operators used with the test
               Operator       Meaning
               -eq            Equal to
               -ne            Not equal to
               -gt            Greater than
               -ge            Greater than or equal to
               -lt            Less than
               -le            Less than or equal to

        E.g.   $ cat
               if test $# -ne 3
                        echo ―you have not keyed in 3 arguments‖
                        exit 3
                        if grep ―$1‖ ―2 > ―3
                                Echo ―Pattern found‖
                                Echo ―pattern not found‖

Short hand for test is widely used as rectangular brackets, and the expression can replace the
word test.
             E.g.      test $x –eq $ $y       [ $x –eq $ $y ]

STRING COMPARITION: The test can be use to compare two strings. Here = is used for
equality and != is used for inequality.
              Test           Description
              -n str         True if string str is not null
              -z str         True if string str is a null string
              s1 = s2                True if s1 = s2
              s1 != s2               True if s1 != s2
              str            True if str is assigned and not null

             E.g.  if [-n ―$pname‖ –a –n ―$flanme‖]; then
                   grep ―$pname‖ ―$flname‖ || echo ―Pattern not found‖
                            echo ―At least one input was a null string‖
                            exit 1
FILE TEST: It can be used to test the various file attributes. E.g. user can test whether a file
has the necessary read, write or executable permissions.

             Test          Description
             -e file       True if file exists
             -f file       True if file exists and is a regular file
             -r file       True if file exists and readable
             -w file       True if file exists and writable
             -x file       True if file exists and executable
             -d file       True if file exists and directory
             -s file       True if file exists and has a size greater than zero

        It is the conditional offered by shell. It matches an expression for more than one
alternative, and uses a compact construct to permit multi-way branching. It also handles string
tests, but in more efficient manner than if.
        Syntax:       case <expression> in
                      pattern1 )    <execute commands> ;;
                      pattern2 )    <execute commands> ;;
                      pattern3 )    <execute commands> ;;

      It matches the expression first to pattern 1, if successful, then executes the commands
associated with it. If it does not matches, then searches for pattern 2. Each command list is
terminated by a pair of semi-colon, and finally with esac.
      E.g.           $ cat
                     echo ―MENU\n
                     1) List of files\n          2) Processes of user\n
                     3) Users of system\n        4) Exit\n
                     Enter your options : \c‖
                     read choice
                     case ―$choice‖ in
                          1) ls –l ;;
                          2) ps –f ;;
                       3) who ;;
                       4) exit

        It can not handle relational and file test. It can only match strings. It is also most
effective when the string is fetched by command substitution. It is also possible to match more
than one pattern.
         E.g. echo ―Do you wish to continue : \c‖
               read ans
               case ―$ans‖ in
                     y | Y) ;;
                     n | N) exit ;;
        Like the shell‘s wild-cards, it also uses filename matching metacharacter *, ? and the
character class.
        E.g. echo ―Do you wish to continue : \c‖
               read ans
               case ―$ans‖ in
                     [yY] [eE] * ) ;;
                     [nN] [oO] ) exit ;;

        The shell does not have any computing features at all; it has to rely on the expr
command. It combines two functions in one; it can perform arithmetic operations on integers
and also manipulate strings to a limited extent. It makes the shell relatively slow, but it can be
useful in handling simple arithmetic tasks. It can perform basic four arithmetic operations.
E.g. $ x=3 y=5
        $ expr 3 + 5
        $ expr $x - $y
        $ expr $y / $x
        $ expr $y % $x
        The operand +,-,* etc., must be enclosed on either side by white space. To use
multiplication operand (*), it has to be used with backspace (\). The most common use of expr
is in incrementing the value of a variable.
E.g. $ x=5
        $ x = `expr $x +1`                       # it is same as x++
        $ echo x

       It repeatedly performs a set of instruction till the control command returns a true exit
Syntax:       while <condition>
E.g.   answer =y
       while [―$answer‖ = ―Y‖]
             echo ―Enter the code and description : \c‖
             read code description
             echo ―$code | $description‖ >> newlist
             echo ―Enter any more (Y/N)? \c‖
             read anymore
             case $ anymore in
                   y*|Y*) answer=Y;;
                   n*|N*) answer=N;;
                       *) answer=y;;
       Suppose the system administrator wants to see the free space available on disks every
five minute, an infinite loop is needed.
       E.g. while true ; do
                       df –t
                       sleep 300
              done &
       At every 5 minutes, user will get information about the free space.

      It is the complement of while loop. It has sense that the loop body is executed
repeatedly as long as the condition remains false.

      It is different in structure from the ones used in other programming languages. There in
no next statement in this for loop.
Syntax:        for <variable> in <list>
                      <execute commands>
      The loop body is the same, but the additional parameters variable and list are used. The
loop body is executed as many times as there are items in the list.
E.g. $ for x in 1 2 3 4
      > do
      >        echo ―The value of x is $x‖
      > done

       The list can consist of any of the expressions that the shell understands and processes-
variables, wild-cards, command substitutions and positional parameter.

   List from variables
E.g. $ for var in $PATH $HOME $MAIL
      > do
      >       echo ―$var‖
      > done
   List from wild-cards
E.g. $ for file in *.c
      > do
      >       cc -0 $file{x} $file
      > done
   List from positional parameters
E.g. $ for pattern in $*
      > do
      >       grep ―$patten‖ emp.lst || echo ―Pattern $pattern not found‖
      > done
   List from command substitution
E.g. $ for file in `cat clist`
      This is most suitable method.

The basename command is used with the for loop to change the extension of group of files.
E.g. $ basename / home / Sunil / project /

If it is used with the second arguments, it strips off the string from the first arguments.
E.g. $ basename abc.txt txt

To rename filename extension txt to doc:
E.g. $ for file in *.txt
        > do
        > leftname = `basename $file txt`
        > $file ${leftname}doc
        > done
It is not shell built-in, but an external command.
   THE here DOCUMENT (<<) (remaining)
         In some situation, when the data that program reads is fixed and fairly limited. The shell
offers a mechanism of placing this data in the shell script itself that uses it; with the << symbol.
It is often referred as here document. It signifies the data is here rather than in a separate file.
Any command using standard input can also have the input from a here document.

        Unlike shell variables, the positional parameters as well as the parameters associated
with it can not be set by making a direct assignment with the = operator. User can put some
values into positional parameters in an indirect manner using set command.

E.g.   $ set 111 222 333
       So $1 = 111, $2 = 222 and $3 = 333.

      This feature is particularly useful for picking up individual fields from the output of a
E.g. $ set `date
      $ echo $*
      sat sep 13 21:12:29 IST 1997

       $ echo ―The date of today is $2/$3, $6‖
       the date of today is sep 13, 1997

      It transfers the contents of positional parameters to its immediate lower numbered one.
This goes on as many times as the statement is called. When called once $2 becomes $1, $3
becomes $2 and so on.
E.g. $ set `date`
      $ echo $*
      sat sep 13 21:12:29 IST 1997

       $ echo ―The date of today is $2/$3, $6‖
       the date of today is sep 13, 1997
    $ shift
    $ echo ―The date of today is $1 / $2 / $3‖


       Communication through the system seems quite natural and necessary. It is less formal
than either speech or paper, and people use it to voice certain views which they would not do
otherwise. The growth of internet has also added to its popularity.

        it is normally invoked by any user to read any message that is sent by the system
administrator. The latter is stored in /user/news. A typical news item is stored in the file dinner
in that directory.
        It is available with the UNIX and SCO UNIX but not with Linux. In multi-user
environment, the clients are scattered within a location. So, it is very necessary to have
communication between them.
E.g. $ news
         Hello friends, Good morning
         <ctrl +d>
        At the client side, when user fires the command news, the message would be displayed.
        Options        Description
        -n             It displays only the filenames of those messages that have not been
        -s             It lists the number of news items that have still not been read.
        -a             It displays the contents of all news items regardless of whether they have
read or                          not.

       It is used to communicate with any person who is currently logged in. One user writes a
message and then waits for the reply from the other. It uses the login name of the recipient as
arguments, and the text of the message from the standard input.
E.g. $ write Sunil                                           # it writes to user named Sunil
       Hi friend how are u? It is jalpa here
       <ctrl +d >
       When write is used interactively, both users need to invoke the command individually. It
establishes two channels, one for the sender and another for the receiver. It is so designed that
it enable the user to send and receive message at the same time, without having to quit to the
       It also takes standard output.
E.g. $ write Sunil < sunil.msg

      But it has one disadvantage. If any user sends you message, that will affect your current
work and you have to answer it. It is by default permitted communication.

        Communication can be disturbing to a user. So user can use the mesg command to
prevent such disturbance.
        $ mesg n               # can not receive message
        $ mesg y               # can receive message – by default
        It is the command that is kept in the .profile by user who want to receive messages. It
affects write, talk command.
        it is an very popular communication command. It is the basis of chat feature that is
widely used in the Internet. There are following reasons for using talk:
        1)     It splits the screen horizontally into two windows; one window shows the received
               data, while the other is used for transmission
       2)    It runs on a TCP/IP network
       It works only if the recipient‘s terminal is enabled (mesg is y)
E.g. $ talk Sunil
       Second user has to use talk command to communicate with the first user. The
advantage of talk over write is that user can easily differentiate between sent and received
messages. The top window displays the sent messages, while the bottom windows show the
received messages.
       It can be terminated by either user entering the interrupt key.
       I is used to mail any user. The advantage with these commands is that user need not
handle mail the moment user is informed of it. But user can reply whenever he/she wishes. It is
one of the most well-known commands in the UNIX repertoire (list) of electronic mail. Even
though it has a host of options and internal commands, few of them are really complex.
Syntax:        $ mail < recipient‘s name>
               <ctrl + d>
       If the recipient is busy with another task, then this command would not interfere in the
execution of that command. When another task gets completed, the recipient would get
message of new mail. If any user wants to check the mail, he/she has to use command mail
without any argument. It would list all the new mail received. It postmarked with the name of
the sender, the date and time of sending it. There is no. of internal command that can be used
with the & prompt when user is checking mailbox.
       It saves message in a mailbox, which normally is placed in the directory
/var/spool/mail/username. But when the message is not saved but only viewed than it would
be saved in the file $HOME/mbox automatically at the time of quitting from mailbox.

Mail Internal Commands:
Option                  Description
+                       To check next mail
-                       To check previous mail
<num>                   To check particular no. of message (E.g. 3 is used to check third
w <m no> < fname>       User can save one or more messages in separate file rather that the
                        default mailbox (mbox).
                        E.g. w 123 note  saves 1, 2, 3 no. of message in the file note
s                       User can save mail message with all header an postmarks
                        E.g. s 134 mailfile  appends message no. 1, 3, 4 in to mailfile.
d                       To delete file from the mailbox. It deletes the message when quitting
from                           the mailbox
u                       To undelete any delete marked mail.
r                       It enables the recipient to reply when the sent message is on display
h                       Prints headers of all messages
m <user>                Forwards mail to another user
q                       Quitting from mailbox.
! <command>             runs UNIX command

      It is not user-friendly, which makes use of the program quite difficult for casual users.


       It is the mail handler generally shipped with most of Linux, not with UNIX. It is a menu-
driven, extremely simple to use and quite powerful. It feels up the entire screen when invoked
by the command name. At the bottom of the screen options are given. The option menu is
straight forward. To check any message, move the highlight up and down to select that the
message and then press <enter>.
       Sending a mail is simple as reading the mail.
Option                Description
-r                    to reply any mail
-z                    to check whether there is any mail in mailbox
q                     quit
s                     send mail

        the pine stands for Program for Internet News and E-mail. It is widely used on the
internet. It was developed by the University of Washington. It combines simplicity and power
using a core set of minimal functions. It can be used without using any manuals. The mailer
can be called up simply by invoking pine. The menu items are neatly laid out. Apart from
sending and receiving mail, user can also maintain the address book. It has context sensitive
help that is invoked by using ? in most cases.
     Viewing Mail: The option i and l are used for the purpose of viewing the contents of the
     folders. A message can be selected using arrow key and then press <enter> key. If user
     has more messages to view, option n can used to see them in turn, while p is used to
     check previous one.
     Composing Mail: The option c is used to compose a message. pine has its own editor for
     composing. It also gives conformation at the time of saving message.
     The Address Book: It is an interesting feature of pine. Here user can enter a person‘s
     details just once so they ca be picked up from the book subsequently (later). From the
     address book itself user can compose message. It also allows spell checking. It also
     provides multimedia attachment.

       It is a versatile (flexible) command having communicative features. When used without
any arguments, it simply produces a list of all logged users. If any user is specified with the
finger command, it works like who.
       It is sometimes necessary to leave behind your schedule and other important information
for others to see. It is not simply possible to send mail to all users. The vacation command
uses the mail forwarding facility, but it‘s used only when the recipient is away on vacation. All
incoming mail will now be saved, and the senders will be automatically sent the message to
indicate that the recipient is away.

                            CHAP 16 MORE FILE ATTRIBUTES

Q      chown and chgrp
       When any file is created, the creator becomes the owner and group to which the user
belongs becomes the group owner. The owner can change the major file attributes, like its
permissions or even ownership. A group owner or others can not change it. When owner copy
a file owned by someone else, the ownership of the copy file is transferred to current user.
There are two commands meant to manipulate the ownership of a file or directory -- chown and

       The chown (CHange OWNership) gives away the ownership of a file to any user. It is
used with the username to whom ownership is to be given away, followed by a list of filenames.
Thus, to renounce (reject, cancel) the ownership of the file can be done using chown.
E.g. $ chown jay file1, file2, file3
       Ownership once surrended, can‘t be reinstated. Once ownership of the file has been
given away to new user, the file permissions pertaining to the owner are now applicable to new
user only. Thus, old user can no longer edit the file, delete it, since it does not have privileges.

       The chgrp (CHange GRouP) command changes the group ownership of the file. It
shares a similar syntax, and can be used by the owner only like chown command. The group
owner of a file is also the group to which the owner belongs. A file thus has dual ownership, and
the rights of these two owners usually vary. To complicate matters further, it is also quite
possible that the group to which the owner belongs may not be the group owner of the file.


         When a file is copied, both the original and copy occupy separate space in the disk.
UNIX allows a file to have more than one name, and yet maintain a single copy in the disk.
Changes to one file are also reflected in the other. The file is then said to have more one link,
i.e., it has more than one name. a file can have as many names as user want to give it, but the
only thing that is command to all of them is that they all have the same inode number. In win
95 and NT, the same principle is called shortcut. But these shortcuts itself contain some disk
space. In UNIX, user can easily know the number of links of a file from the fourth column of the
ls –l listing. This number is normally 1 but exceed this figure for linked lists.

       The files can be linked using ln command, which takes two filenames as arguments.
E.g    $ ln emp.lst employee

       The –i option shows that the links of file. All the linked files have same status; it‘s not that
one file contains the actual data and the others don‘t. The file has simple different aliases. So
changes done in one file automatically available in the other files. A file is considered to be
completely removed from the system when its link count drops to zero. Sometimes, it is difficult
to remove all links to a file, especially when they exist in multiple directories. It is also called
hard link.

       The UNIX system also features another form of link, the symbolic link. This link being
more flexible is also known as a soft link. The hard link has two limitations.
       1) User can‘t have two linked files in two file systems.
       2) User can‘t link a directory even within the same file system
       The soft links points to the file which actually has the contents. The concept of shortcut
in win- 95 is the soft link. The link can be created using –s option with ls command.

                         CHAP 17 SYSTEM ADMINISTRATION

         The tasks of job of system administrator involves the management of the entire system,
ranging from maintaining security, performing backups and disk management, to providing a
reliable service to all users. The system administrator is sometimes known as super user. He
has vast posers, having access to everything.
         The UNIX provides a special login name for the use of system administrator. It is called
root. It comes with system itself. It also has a password.
         The command invoked by the administrator has a greater chance of success than those
issued by others. There are several commands that are reserved for his exclusive use; no other
user will be able to execute them. He can change attribute of file and can initiate or kill any
process. No file can ever be secure from him. The administrator‘s privileges are as follow:

   On some systems, the clock moves at an incorrect sped, and frequent corrections are
necessary. The administrator use date command with a numeric argument to set the system
date. This argument is usually an eight-character string of the form MMDDhhmm.

B) COMMUNICATION WITH USERS: wall and calendar
   As an administrator user has to communicate with user constantly, the usual command used
are write, talk and mail. But user also has the exclusive facility of addressing all users (wall) or
reminding of their engagement for the day and next (calendar)

   Faulty programs or processes can occupy disk space in no time. It is desirable to impose a
restriction on the maximum size that a user can be permitted to create. It can be achieved using
ulimit command. The default expressed in units of 512 bytes of set inside the kernel.


       The booting and shutdown processes are some of the function of administrator daily.
Like DOS, we can not only switch on the machine and work. But we have to issue a series of
command in sequence or responding to some prompts. A separate series of commands are
required to shutdown the UNIX. But these functions are generally automated by use of vender-
supplied scripts that is edited by administrator to suit a particular environment.
       Before the system is started, the peripherals should be turn on which are required
immediately. It is needed because when the kernel is loaded the device drivers for those
peripherals are powered and connected. When peripherals are switched on, the computer itself
can be turn on.
       The machine then goes through a complex series of processes to complete the boot
cycle. The exact sequence of the steps followed is depending upon s/w to h/w used.
       First event is the loading of the kernel. So file would be loaded in main memory. The
kernel then starts spawning further processes. The most important of which is init. It becomes
the parent of all shell.
       The system can be set up in a no. of modes (called run levels) that are controlled by init.
Following two are the well known:
       1)         Single User Mode: it is important for user who uses it to perform his
                  administrative tasks like checking and backing up individual files system. Other
                  users are prevented.
       2)         Multi-User Mode: individual file systems are mounted and system daemon are
                  also started. Printing is possible only in multi-user mode.

     It usually performs following activities:
     1)    Notifies users with wall about the system going down and directive to log off. Users
           are then expecting to close all their files and log out of the system within a minute or
           so. The shutdown itself sleeps for a minute after mailing the first message and may
           issue a reminder or two.
     2)    Sends signals to all running processes so that they can terminate normally.
     3)    Logs users off and kills remaining processes
     4)    Unmounts all secondary file system, i.e., detaches them from the root file system.
     5)    Writes information about file system status to disk to preserve the integrity of the file
     6)    Notifies users to reboot or switch off, or moves the system to single-user mode

      When the message appears on the screen, the machine can be considered to have
completed the shutdown sequence successfully. The system can be switched off or rebooted.
On most systems the shutdown is shell scripts, which is too often edited by administrator. It
has to be run from the root user account, and in some installation, is invocable only from the
console. It requires the knowledge of the root password, while booting into multi-user mode it
does not required.
      There is also a reboot command that cuts short the normal shutdown procedure and
reboots the system; users are not warned even. The command haltsys, which brings down the
system instantly. Their use is not recommended on multi-user mode.


        This is really crucial task performed by administrator. Although a lot of disks are added to
the system, it will be scramble (mix up) for space. Users often forget to remove the files they no
longer required. There are a number of files, in the directories /tmp and /usr/tmp that tend to
accumulate during the day. If his build-up is not checked, the entire disk space will eventually
be full. So it would slowdown the system performance.
        So administrator has to monitor the space and remove that have outlived their utility.
Sometimes some users may use more space than they are supposed to use. It can be
achieved by command df and du. It can be issued by any user. Both of them report disk usage
or the free space in terms of blocks, the unit of measurement is 512 bytes.

1) The df command
      It reports the amount of free space available on the disk. The output always reports for
   each file system separately. There are four file systems, of which the first tow is always
   created by system installation. The system will continue to function until the free blocks or
   inodes are eaten away, whichever occurs earlier. The total free space in the system is the
   sum of the free blocks of the four file system.

2) The du command
       Sometimes user wants to find out the consumption of a specific directory tree rather than
   an entire file system. The du command reports usage by a recursive examination of
   directory tree. By default, it lists the usage of each sub-directory of its argument, and finally
   produces a summary.

3) pack, compress, gzip and zip: file compression
      There will be always be a number of files that are required moderately, and which user
   won‘t like to back up an restore repeatedly. The pack and compress gives facility of
   compression utilities and release some disk space. The pack is quite inefficient in
   compression. The compress is quite fast and compress well.

       The uncompress command is used to produce back the original file.


       The administrator is responsible for the safety of the data that resides in the system. It is
the part of duties of administrator that the files should be backed up and determine the
periodicity of such backups. The effectiveness of the backup is determined by your ability to
restore lost or corrupted data files easily.

       User often accidentally deletes their own files and then wants to restore them. The
administrator has to plan his backups carefully so that he doesn‘t back up the same file over and
over again even though it has not bee accessed from a long time. Some files are modified more
often than others, while some are not accesses at all for months. The classical theory for the
backup is that there should be a complete backup of all files once a week, and a daily
incremental backup of only those files which have been changed or modified. But the routine
may be modified depending on the size and nature of installation.

      If administrator can make all the data fit into a single tape, he can leave the backup
process unattended too so that he doesn‘t need to change tapes. The backup device can be
magnetic or a cartridge tape, a floppy diskette, or even a disk file.

        The two most popular programs for backup are cpio and tar. Both combines a group of
files into a single file, called archive file, with suitable headers preceding the contents of each
file. The cpio command is often preferable to tar for many reasons describe as follow:

1) Since cpio can take its list from find, it can back up files selectively, while tar is used for
   complete directory trees.
2) The cpio skip corrupted file headers or skip over those files when I/O problems are
   encountered during restoration
3) Files are packed more efficiently with cpio, thus using lesser space.
4) The cpio is also used almost universally for backing up fie system. The tar is not used for
   device files.

       It is always preferable to maintain a file list for every backup. When user asks for
particular file, from the list the administrator can look up for the particular file.


       In addition to routing backup, administrator has to back up individual file systems.
Backup manager is a fairly complete system which lets the administrator schedule and
implements his backups in a systematic manner. If the system crashes and UNIX has to be
reinstalled, the administrator would not go through the tedious process of installing all
peripherals separately. The root and boot file systems can be restore from the backup file.


       The command can be used to copy files to and from a backup device. It uses standard
input to take the list of filenames, and then copies them with their contents and headers, into a
single archive that is written to the standard output. It can be used with piping and redirection.
It uses two ―key‖ options –o and –i.
    Backing up files

       Ls can be used to generate a list of filenames for cpio to use as input. The –o option is
    used to create an archive which can be redirected to a device file.
    E.g.      $ ls | cpio –ov > /dev/rdsk/f0q18dt

       The –v option makes cpio operate in verbose mode, so that the filenames is seen on the
    terminal when it is being copied.

    Incremental backup: find can also produce a file list, so any file that satisfy its selection
    criteria can be backed up.
    Multi-volume backup: when the created archive in the backup device is larger than the
    capacity of the device, cpio prompts for inserting a new diskette into the drive. When cpio
    pause to take input, the device name should be entered. If there are two floppy drives on a
    machine, user can alternate between two device names.

    Restoring files
        A complete archive or selected files can be restored with the –i key option. To restore all
the files that were backed up with a previous cpio command, the shell‘s redirection operator (<)
must be used to take input from the device.
        When restoring sub-directories, cpio assumes that the sub-directory structures are also
maintained in the hard disk. But it can also create them if it is not present. The –d option
overwrites it. It also accepts a quoted wild-card pattern, so that multiple files fitting the patter
can be restores.
Preserving Modification Times: By default, when a file extracted, its modification time is set to
the time of extraction. It would not be modified at the time of restoration. So it creates problem
in incremental backup. The –m option is used to restore last restoration time.

       Options       Description
       -d            Creates directories as and when needed
       -c            Writes header information in ASCII character from portability
       -r            Renames files in interactive manner
       -t            Lists file in archive
       -u            Overwrites newer file with older version
       -v            Verbose option
       -m            Retains original file modification time
       -f exp        Copies all files except those in exp
       -Csize        Sets input-output block size to size bytes


       The command has been in existence before the emergence of cpio. Ti no only creates
archives on tapes, but supports floppies as well. It does not write to the standard output, but
crates an archive in the media. It is a versatile command with certain exclusive features no
found in cpio.
       1)       It doesn‘t use standard input to obtain its file list. It accepts file and directory
                names as arguments
       2)       It copies one or more entire directory tree, i.e., it operates recursively
       3)       It can create several versions of the same file in a single archive
       4)       It can append to an archive without overwriting to entire archive

        It is used with a number of key options—the common ones are –c (copy), -x (extract) and
–t (list). One and only one of these key options ha to be present. The –f option is used to
specify device name.
    Backing up files

      When files are copied with absolute pathnames. They can be restored in the same
  directory. But to change the directory user has to specify path. The advantage of tar is it
  can copy an entire directory tree with all its sub-directories, with or without hidden
  directories. The files here are backed up with their relative pathname, assuming that they all
  fie in one diskette. They do not accommodate them as much as possible. It quits program
  without warning.

  Multivolume backup: the –k option is used for the purpose.

  Restoring files
     It can be accomplished using –x option. When no file or directory name is specified, it
  restores all files from the backup device.

                            CHAP 18 TCP/IP NETWORKING

       Every frame traversing the network goes out to all machines, so the network traffic grow
as the number of machines connected to the network increases. So the network should be
subdivided into subnets. Routers are used to connect all subnets. This feature is also offered
by TCP/IP.
       The division of network into subnets has no significance to a computer outside the
network. It will simply look at the first octet and treat all frames address. For this TCP/IP
provides a means of identification, which is known as the subnet mask. It is a string of four
octets, where bits represented by the network address, along with the borrowed bits are set of 1.
       E.g. if user borrows the entire third octet from the host address, the first 24 bits of the
address are set of 1. the subnet in binary will then look like:
       11111111 11111111 11111111 00000000               in decimal it is

        All networks have a subnet mask that determines whether it is subnetted or not.
Borrowing an entire octet for the purpose of subnetting makes sense only when user really
requires a larger number of subnets. There is no need to borrow the entire third octet; only the
first two bits are sufficient. TCP/IP also allows this. User can use any number of bits from the
host address.


      It offers to connect to a remote UNIX system. It belongs to the DARPA command set.
Machine‘s IP address is used with this command as argument.
E.g $ telnet
      Now user has to enter login name at the prompt and then the password to gain access to
the remote machine. As long user logged in, anything he type is sent to the remote machine,
and the user‘s machine act as a dumb terminal. When logged out, user gets his local shell.

       Every device in a network is assigned an IP address by the network administrator. This
is 32-bit number and is unique in the network. Each of octets has some significant meaning.
E.g. 11000000 10101000 00000001 10100000          

       First this address is converted to dotted decimal notation. So it is equivalent to above
decimal no. Every IP address consists of two portions. A network address and a host address.
All host has same network address but having different host address. The network address
may occupy one to three octets from the left, while the rest are reserved for host addresses. In
above example 192.168.1 is network address while .160 is a host address.
       Maximum no. of that each octet can have is 255. So the lowest address can be
while the highest is The number of octets reserved for the network address
and the value of the first octet determines the class to which the network belongs. It is having
three classes.
       1) Class A: This is provided to very large organization, but now a days they are not
           assigned to any company.
       2) Class B:
       3) Class C:

      Some significance in TCP/IP are
      1) Every network itself has an address
      2) Every network needs a separate broadcast address
      3) A separate address is needed for loopback
        IP addresses are used by many utilities like telnet. But many applications usually access
 these machines by their names rather than IP address, because they are difficult remember. So
 they are given naming convention, which can be used by users.

 Q      PRINTER MANAGEMENT (chap 26)

          It is an important part of the administrator‘s job, and in large installation can often take a
 lot of time. UNIX provides a spooling sub-system featuring a number of commands which
 ensure that spooling takes place in an orderly manner. It involves managing the print queues,
 adding and removing printers, starting and stopping the sub-system. It must make of two
 following components:

               1) Commands used by the user like lp, cancel
               2) The administrator command like lpadmin, lpsched, lpshut, accepts and
                  reject, enable and disable.

       No user is allowed direct access to the printer. One has to spool a job along with others
 in a print queue. Spooling ensures the orderly printing of jobs, relieving the user from the
 necessity of administering the usage of print resources. It is provided by lp command.
E.g.   $ lp chap01
       request id is pr1-320 (1 file)

        The prompt is returned immediately after the job has been submitted. It notifies the
 request-id, a combination of the printer name (pr1) and the job number (320). The file is not
 actually printed at the time the command is invoked, depending upon the number of jobs already
 lined up in the queue. Several users can print their files in this way without conflict. The output
 from the printer would be a hard copy of the actual file with title page mentioning the username,
 request-id and date.

       The lp command accepts the request if a default printer has been defined by the
 administrator. If it has more than one printer, administrator has to specifies the name of printer.

        Option        Description                                 E.g.
        -d            specifies the printer name.                        $ lp –dlaser chap01
        -t            gives title to the first page.              $ lp –t”Hello” chap01
        -m            it mails user after the file has been printed
        -n            for multiple copies                         $ lp –n3 –m chap01

        To cancel any job cancel command is used.
 E.g.   $ cancel laser                 cancels current job on printer laser
        $ cancel pr1-320         cancels job with ID pr1-320


       The fdisk command is used to create, delete and activate partitions. The command is
 also used I n DOS for the same purpose, but operates different in Linux. Upto four partitions
 can be created in each hard disk.

       The built-in UNIX feature of delaying the updations of the disk superblock by its in-
memory copy leaves a lot of scpe for file system inconsistency. If the poser goes off before the
superblock was written to disk, an incorrect superblock and often some inodes are left behind.
The file system then loses its integrity and needs immediate rectification. The checking is done
during the next startup. There are many differences that could lead to file system corruption,
and the most common are:
       1) A block marked as free but actually in use, or a used block marked as free
       2) A block marked free, nor in use, or having a bad block number that is out of range
       3) Two or more inodes claiming the same disk block
       4) Mismatch between the file size specified in inode and the number of data blocks
           specified in the address array.
       5) A file not having at least one directory entry or having an invalid file type specified in
           the inodes.

       The fsck command is used to check and repair a damaged file system. It checks in five
phases, and the output is obtained when the file system is consistent. When the file is
corrupted, messages and questions are seen on the system cosole.


        It is a daily job of an administrator. They are run by automated shell scripts which are
changed quite infrequently. It is initiated at the time of system startup. The kernel is loaded into
memory, and it then starts spawning further processes. It has PID 1, which is responsible for
the birth of all subsequent processes. There are two main tasks of init processes.
        1) It controls the system states and decides which processes to run for each state.
        2) It spawns a getty process fro every terminal so that users can log in.

       It also makes sure that all system daemons are running. The lpsched command
monitors the liner printer spooler for jobs that have been queued for printing. The cron
command is the system‘s chronograph. The gated is the TCP/IP daemon which takes care of
routing. The inetd is the master internet daemon, which spawns further daemons as and when
required. While the init is parent of all these.
       It is also responsible for keeping the system in different states, called run levels.
       1        System shutdown
       2        System administration rule
       3        Full multi-user mode in SCO UNIX
       4        Full multi-user mode in LINUX
       6        Shutdown and reboot mode
       S or s Single user mode

        When the system is booted, init first enters the run level 1 or S, it puts the system in
single-user mode. This mode id used by the administrator to perform his administrative tasks
(like checking the file system and taking an off-line backup). But it can use printer, file system
can not be mounted, others users are prevented.

     It takes all its instructions from this file. Its fields determine the processes that should be
spawned for each of the init states and the programs to run at the communication ports.


       The interesting feature about a file system is, once it is created, it is a logically separate
entity with its own tree structure and root directory. It is treated as a stand-alone mode; the
main file system does not even know of its existence. These file systems unite to become a

single file system at the time of booting. The root file system then becomes the main file
system, and its root directory is the directory of the unified file system. It happens because of
mounting process. When all these secondary file system attach them (mounted) to the main
file at different points.

       The mount and unmount commands are used. The end result of mounting is that the
user sees a single file system in front of herself, because the file movement is not between the
hard disks.

    The mount command
        To mount file system to the root file system, an empty directory must first be made
available in the main file system. The root directory of the new file system has be mounted on
this directory. The point at which this linkage takes place is called the mount point. The mount
command takes two arguments.
               1) The name of the file system and
               2) The directory under which it is to be mounted.

       The files are mounted at the start up time or manually. If rcmount is yes then the file
system is mounted during startup. The mounting information can be created for the floppy drive
and the CD-ROM also. The noauto option specifies that it is not mounted at the time of system
       Option        Description
       -f            It is used to specify the type of file system that is to be mounted, which is
necessary                             when CD-ROM is mounted
       -r            It mounts a file system in read-only mode.
       -a            all files in the directory

    The unmount command
       Unmounting can be achieved with the umount command, which requires either the file
sytem name or the mount point as argument. User can not unmount a file system unless user is
placed above it. It is not possible to unmount the /usr file system as long as the file is being
       File system are mounted during system startup, and unmounted when the system is shut
down. If the file system is not clean, it will fail to mount, in which case it has to be checked for
consistency. There is also a system configuration file which specifies how and when these file
system are mounted an unmounted.

      The term user means the name of a project or an application, where a group of users
having similar functions can use the same username to use the system. The UNIX system
provides a number of services related to the creation and maintenance of user accounts.

   ADDING USER: useradd
      The administrator has to associate each user with a group, and the permissions must be
decided that have to be set for both the user and her group. Adding a user involves setting of
the following parameters:
      1) An UID and User name
      2) A GID and Group name
      3) The home directory
      4) The login shell
      5) The mailbox

     6) The password

       It the user is placed in a new group, an entry for the group has to be created in
/etc/group. It must have one primary group, and also secondary group. The file contains all
the named groups of the system and few lines of the file.
       Option       Description
       -u           UID
       -g           GID


   MODIFYING AND REMOVING USERS: usermod and userdel


Shared By:
Description: Unix tutorial part 3