Eswi Unit-1

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 43

ESSENTIALS OF SYSTEM AND WEB INTERFACING

UNIT-I

COMPUTER SYSTEM: Introduction, Defining Computer, Exploring the Basic Parts of a


Computer, Describing Computer Hardware, Describing Computer Software.
Exploring an Operating System- Introduction to functions of Operating System, Introduction
to UNIX, Why UNIX, Architecture.

UNIX SHELL Introduction: Introduction to UNIX Shell, simple commands, Syntax of


commands, uname and bc commands, variables, quotes. Filesystem layout. File related
commands, Types of files, links- hard and soft links, Operations on Directories. Security and
permissions. Redirection. Job control- ps, fg and bg.
COMPUTER SYSTEM:
A computer is a machine that accepts data as input, processes that data using
programs and outputs the processed data as information.
Initially, computers were developed to perform mathematical operations, but later on, they
were used to store the result of those operations, which with the time leads to the storage of
other data or information.
 Data is a collection of unprocessed facts, figures, and symbols. e.g. Ram, age, 32,
years, old
 Information is a processed form of data. It is organized, meaningful, and useful. e.g.
Ram is 32 years old. Or Ram’s age is 32 years.

A computer can be defined as an advanced electronic device that takes raw data as input from
the user. It uses a set of instructions (called program) to process the data and give the result
(output). The result can be used immediately or saved for future use.

Basic Parts of a Computer:


The hardware in a computer is the combination of devices that can be seen and
touched.
Every computer, small or large, is made up of three basic types of devices:
I. Input devices
II. Output devices
III. The CPU(Cabinet)

I. Input devices
Input device enables the user to send data, information, or control signals to a
computer. The Central Processing Unit (CPU) of a computer receives the input and processes
it to produce the output.

Some of the popular input devices are:

 Keyboard
 Mouse
 Scanner
 Microphone

II. Output Devices:


The output device displays the result of the processing of raw data that is
entered in the computer through an input device. There are a number of output devices that
display output in different ways such as text, images, hard copies, and audio or video.

Some of the popular output devices are:

 Monitor
 Printer
 Projector
III. The CPU(Cabinet)
The computer cabinet is nothing but an enclosure that allows other computer parts to
be installed inside them; such parts are Motherboard, Computer hard disk drive, SMPS,
RAM, Optical Drives, Processor, etc.
The cabinet also possesses connecting ports and buttons. They are used to connect the
keyboard, mouse, printers to the motherboard.

The cabinet’s main advantages are that it protects all the sensitive and essential parts of the
computer system from water, dust, and physical damage, as the parts are safely assembled
inside the computer cabinet.

Motherboard:

The computer motherboard is designed and developed on PCB, which stands for the printed
circuit board. The motherboard is the essential part of any computer system responsible for
holding or connecting different electronic components like RAM slots, CPU, SATA, PATA
slots, expansion slots, bios chips, capacitor, coil, and resistors.

CPU {Central Processing Unit}

The heart of the computer system is the processor unit. It consists of the Arithmetic and
Logic Unit (ALU) which executes most computer operations (arithmetic and logical) and the
Control Unit which acts as the nerve centre that sends control signal to all other units.

The control unit and ALU are usually many times faster than other devices connected to a
computer system. This enables a single processor to control a number of external devices
such as video terminals, magnetic tapes, disk memories, sensors, displays and mechanical
controllers, since they are much slower than the processor.
There are two categories of memory:

• Primary memory and

• Secondary memory (or external memory).

Primary Memory is very fast as data and programs must be in the primary memory for
execution. Random Access Memory (RAM) and Read Only Memory (ROM) are both
primary memories.

 Random Access Memory refers to memory that can be selected and used
randomly. The information stored here disappears the very moment the machine is
turned off. It is also referred to as volatile memory.
 Read Only Memory is permanently built into the computer at the time of
production. The information from this memory can only be read and it is not
possible to write fresh information into it. It permanently stores a set of
instructions which instructs the computer how to work. After we switch on the
computer, it uses instructions stored here to carry out a series of tasks
automatically, before we can actually use the computer.

 Secondary Memory or Auxiliary Memory: The content on the RAM is erased


when electric power is switched off. So, it becomes necessary to store this data for
future use, somewhere else. Since, primary storage is expensive too; we need a
relatively cheaper form of backup storage which can store vast quantities of
information. Thus, Secondary Memory devices become an important part of the
computer

S. No. Key RAM ROM

Definitio RAM stands for Random ROM stands for Read Only
1
n Access Memory. Memory.

Data RAM data is volatile. Data is ROM data is permanent. Data


2 Retention present till power supply is remains even after power supply
present. is not present.

Data RAM data can be read, erased ROM data is readonly.


3
Access or modified.

Usage RAM is used to store data that ROM is used to store data that in
4 CPU needs for current needed to bootstrap the computer.
instruction processing.

5 Speed RAM speed is quite high. ROM speed is slower than RAM.

CPU CPU can access data stored Data to be copied from ROM to
6 Access on RAM. RAM so that CPU can access its
data.

Capacity RAM memory is large and ROM is generally small and of


7
high capacity. low capacity.

Usage RAM is used as CPU Cache, ROM is used as firmware by


8
Primary Memory. microcontrollers.

9 Cost RAM is costly. ROM is cheap.

SMPS {Switch Mode Power Supply}


The SMPS {Switch Mode Power Supply} is used to provide electric current to the parts of
the device. The primary function of SMPS is to convert A.C. voltages to D.C. voltages.

Software
The software of a computer system is the combination of programs written to make
the computer a multipurpose machine. It is divided into two different types: system software
and application software.
System software consists of the set of programs that serve the computer itself; that is, its
primary purpose is to support the computer. It generally consists of an operating system and a
set of support programs, such as disk copy, that provide general functionality.
Application software consists of programs that are written to solve users' problems. They
can range from everyday word processors to a specialized application that supports the
operation of a dental office.

The Operating system:

The operating system is a special category of system software that manages all operating
facets of the computer; it gives the computer its heart and character. UNIX is an operating
system. As such, it is different from other common operating systems such as DOS,
Windows, and the Mac OS. Because it makes the computer what it is, an operating system is
the most important part of a system's software.

An Operating System (OS) is a software that acts as an interface between computer


hardware components and the user. Every computer system must have at least one operating
system to run other programs.
An operating system provides three essential capabilities: It offers a UI through a CLI or
GUI; it launches and manages the application execution; and it identifies and exposes system
hardware resources to those applications
UI. Every operating system requires a UI, enabling users and administrators to interact with
the OS in order to set up, configure and even troubleshoot the operating system and its
underlying hardware. There are two primary types of UI available: CLI and GUI.

The CLI, or terminal mode window, provides a text-based interface where users rely on the
traditional keyboard to enter specific commands, parameters and arguments related to
specific tasks.
The GUI, or desktop, provides a visual interface based on icons and symbols where users rely
on gestures delivered by human interface devices, such as touchpads, touchscreens and
mouse devices.The GUI is most frequently used by casual or end users that are primarily
interested in manipulating files and applications, such as double-clicking a file icon to open
the file in its default application.

Functions of Operating system:


1. Memory Management
It is the management of the main or primary memory. Whatever program is executed, it has to be
present in the main memory.  Main memory is a quick storage area that may be accessed directly by
the CPU. When the program is completed, the memory region is released and can be used by other
programs. Therefore, there can be more than one program present at a time. Hence, it is required to
manage the memory.
The operating system:

 Allocates and deallocates the memory.

 Keeps a record of which part of primary memory is used by whom and how
much.

 Distributes the memory while multiprocessing.

 In multiprogramming, the operating system selects which processes acquire


memory when and how much memory they get.
2. Processor Management/Scheduling
Every software that runs on a computer, whether in the background or in the frontend, is a
process. Processor management is an execution unit in which a program operates. The operating
system determines the status of the processor and processes, selects a job and its processor,
allocates the processor to the process, and de-allocates the processor after the process is
completed.

When more than one process runs on the system the OS decides how and when a process will
use the CPU. Hence, the name is also CPU Scheduling. The OS:

 Allocates and deallocates processor to the processes.

 Keeps record of CPU status.


Certain algorithms used for CPU scheduling are as follows:

 First Come First Serve (FCFS)

 Shortest Job First (SJF)


 Round-Robin Scheduling

 Priority-based scheduling etc.

Purpose of CPU scheduling


The purpose of CPU scheduling is as follows:

 Proper utilization of CPU. Since the proper utilization of the CPU is necessary.
Therefore, the OS makes sure that the CPU should be as busy as possible.

 Since every device should get a chance to use the processor. Hence, the OS makes
sure that the devices get fair processor time.

 Increasing the efficiency of the system.

3. Device Management
An operating system regulates device connection using drivers. The processes may require
devices for their use. This management is done by the OS. The OS:

 Allocates and deallocates devices to different processes.

 Keeps records of the devices.

 Decides which process can use which device for how much time.
4. File Management
The operating system manages resource allocation and de-allocation. It specifies which process
receives the file and for how long. It also keeps track of information, location, uses, status, and
so on. These groupings of resources are referred to as file systems. The files on a system are
stored in different directories. The OS:

 Keeps records of the status and locations of files.

 Allocates and deallocates resources.

 Decides who gets the resources.


5. Storage Management
Storage management is a procedure that allows users to maximize the utilization of storage
devices while also protecting data integrity on whatever media on which it lives. Network
virtualization, replication, mirroring, security, compression, deduplication, traffic analysis,
process automation, storage provisioning, and memory management are some of the features
that may be included. The operating system is in charge of storing and accessing files. The
creation of files, the creation of directories, the reading and writing of data from files and
directories, as well as the copying of the contents of files and directories from one location to
another are all included in storage management.

The OS uses storage management for:

 Improving the performance of the data storage resources.

 It optimizes the use of various storage devices.

 Assists businesses in storing more data on existing hardware, speeding up the data
retrieval process, preventing data loss, meeting data retention regulations, and
lowering IT costs

What are the functions of Operating System

 Security – For security, modern operating systems employ a firewall. A firewall


is a type of security system that monitors all computer activity and blocks it if it
detects a threat.

 Job Accounting – As the operating system keeps track of all the functions of a
computer system. Hence, it makes a record of all the activities taking place on the
system. It has an account of all the information about the memory, resources,
errors, etc. Therefore, this information can be used as and when required.

 Control over system performance – The operating system will collect


consumption statistics for various resources and monitor performance indicators
such as reaction time, which is the time between requesting a service and
receiving a response from the system.

 Error detecting aids – While a computer system is running, a variety of errors


might occur. Error detection guarantees that data is delivered reliably across
susceptible networks. The operating system continuously monitors the system to
locate or recognize problems and protects the system from them.

 Coordination between other software and users – The operating system (OS)
allows hardware components to be coordinated and directs and allocates
assemblers, interpreters, compilers, and other software to different users of
the computer system.

 Booting process – The process of starting or restarting a computer is referred to


as Booting. Cold booting occurs when a computer is totally turned off and then
turned back on. Warm booting occurs when the computer is restarted. The
operating system (OS) is in charge of booting the computer.
Introduction to UNIX

The Unix operating system is a set of programs that act as a link between the
computer and the user.
The computer programs that allocate the system resources and coordinate all the details of the
computer's internals is called the operating system or the kernel.
Users communicate with the kernel through a program known as the shell. The shell is a
command line interpreter; it translates commands entered by the user and converts them into
a language that is understood by the kernel.
 Unix was originally developed in 1969 by a group of AT&T employees Ken
Thompson, Dennis Ritchie, at Bell Labs.
 There are various Unix variants available in the market. Solaris Unix, AIX, HP
Unix and BSD are a few examples. Linux is also a flavour of Unix which is
freely available.
 Several people can use a Unix computer at the same time; hence Unix is called
a multiuser system.
 A user can also run multiple programs at the same time; hence Unix is a
multitasking environment.

Why UNIX

Multitasking: A UNIX operating system is a multitasking operating system that


allows you to initiate more than one task from the same terminal so that one task is performed
as a foreground and the other task as a background process.

Multi-user: UNIX operating system supports more than one user to access computer
resources like main memory, hard disk, tape drives, etc. Multiple users can log on to the
system from different terminals and run different jobs that share the resources of a command
terminal. It deals with the principle of time-sharing. Time-sharing is done by a scheduler that
divides the CPU time into several segments also called a time slice, and each segment is
assigned to each user on a scheduled basis. This time slice is tiny. When this time is expired,
it passes control to the following user on the system. Each user executes their set of
instructions within their time slice.

File Security and Protection: Being a multi-user system, UNIX makes special


consideration for file and system security. UNIX has different levels of security using
assigning username and password to individual users ensuring the authentication, at the level
providing file access permission viz. read, write and execute and lastly file encryption to
change the file into an unreadable format.
Command Structure: UNIX commands are easy to understand and simple to use.
Example: "cp", mv etc. While working in the UNIX environment, the UNIX commands are
case-sensitive and are entered in lower case.

Open Source: UNIX operating system is open source it means it is freely available to


all and is a community-based development project.

UNIX Tools and Utilities: UNIX system provides various types of tools and utilities
facilities such as UNIX grep, sed and awk, etc. Some of the general-purpose tools are
compilers, interpreters, network applications, etc. It also includes various server programs
which provide remote and administration services.

Unix Architecture:

UNIX consists of four major components: the kernel, the shell ,the standard set of
utilities and application programs.

The kernel

The kernel is the heart of the UNIX system. It contains the two most basic parts of the
operating system: process control and resource management. All other components of the
system call on the kernel to perform these services for them.

The Shell
The shell is the part of UNIX that is most visible to the user. It receives and interprets the
commands entered by the user. In many respects, this makes it the most important component
of the UNIX structure. It is certainly the part that we, as users, get to know the most. To do
anything in the system, we must give the shell a command. If the command requires a utility,
the shell requests that the kernel execute the utility. If the command requires an application
program, the shell requests that it be run.

There are two major parts of a shell. The first is the interpreter. The interpreter reads your
commands and works with the kernel to execute them. The second part of the shell is a
programming capability that allows you to write a shell (command) script. A shell script is a
file that contains shell commands that perform a useful function. It is also known as a shell
program.
There are three standard shells used in UNIX today.
 The Bourne shell, developed by Steve Bourne at the AT&T Labs, is the oldest.
Because it is the oldest and the most primitive, it is not used on many systems today.
An enhanced version of the Bourne. shell, called Bash (Bourne again shell), is used in
Linux.

 The C shell, developed in Berkeley by Bill Joy, received its name from the fact that its
commands were supposed to look like C statements. A compatible version of the C
shell, tcsh, is used in Linux.
 The Korn shell, developed by David Korn, also of the AT&T Labs, is the newest and
most powerful. Because it was developed at the AT&T Labs, it is compatible with the
Bourne shell. We use the Korn shell for our examples in the first part of this text. We
discuss the other shells when we discuss script programming.

Standard
Shells

Bourne($) CShell(%) Korn($)

Bash($)
tcsh(%)

Utilities:

There are literally hundreds of UNIX utilities. A utility is a standard UNIX program that
provides a support process for users. Three common utilities are text editors, search
programs, and sort programs.

Applications
Applications are programs that are not a standard part of UNIX. Written by systems
administrators, professional programmers, or users, they provide an extended capability to the
system. In fact, many of the standard utilities started out as applications years ago and proved
so useful that they are now part of the system. We dis cuss writing applications when we
cover shell script writing in the second half of the text.

Syntax of Command:

Commands are entered at the shell prompt. You must see the prompt, such as the Korn
shell $ prompt, before you can enter a command. Every command must have a verb and may
also have options and arguments. The command format is:

verb [options] [arguments]

The brackets indicate that the options and arguments are optional. We use this when we
describe individual commands. If an option or argument is in brackets, it is optional. If it is
not in brackets, it is required.
The verb is the command name. The command indicates what action is to be taken. This
action concept gives us the name verb for action. The option modifies how the action is
applied. For example, when we display the date, we can use an option to specify if we want
the time in Greenwich Mean Time or local time. Options are usually one character preceded
by a minus sign or a plus sign. Many commands, however, have multiple options available.

Finally, the argument provides additional information to the command. For exam ple, when
displaying the contents of a file, an argument can be used to specify the name of the file.
Some commands have no arguments, some accept only one argument, and some accept
multiple arguments. You must know, for each command you use, what are the options and
what are the arguments.
The general format or syntax of a command appears in below figure

The name of the


command

Verb Options arguement1 arguement2… arguementn

Command Modifier
Usually one character
preceded by +/-
Arguments can be
1.More information
2.Object Identifiers
3.Name of files

Simple Commands:

 date
 cal
 who
 passwd
 echo
 man
 uname
 bc

Date(date) Command
The date command displays the system date and the time. If the system is local-that is,
one in your own area-it is the current time. If the system is remote, such as across the country
somewhere, the reply will contain the time where the system is physically located.

Syntax:
$date [OPTION]... [+FORMAT]
Options:

Date format:
FORMAT is a sequence of characters which specifies how output appears. It comprises some
combination of the following sequences:

%A The full weekday name (e.g., Sunday).

%b The abbreviated month name (e.g., Jan).

%B Locale's full month name (e.g., January).

%c The date and time (e.g., Thu Mar 3 23:05:25 2005).

%C The current century; like %Y, except omit last two digits (e.g., 20).
%d Day of month (e.g., 01).

%p Locale's equivalent of either AM or PM; blank if not known.

%r Locale's 12-hour clock time (e.g., 11:11:04 PM).

%R 24-hour hour and minute; same as %H:%M.

%x Locale's date representation (e.g., 12/31/99).

%X Locale's time representation (e.g., 23:13:48).

%y Last two digits of year (00..99).

%Y Year.
By default, date pads numeric fields with zeroes. The following optional flags may
follow '%':

Calender (cal) Command:


The calendar command cal ,displays the calendar for a specified month or for a year.
Syntax:
$ cal [options] [[[day] month] year]
The rectangular bracket means it is optional, so if used without an option, it will display a
calendar of the current month and year. 
Options:

-1, --one
Display single month output. (This is the default.)
-3, --three
Display three months spanning the date.
-n , --months number
Display number of months, starting from the month containing the
date.
-S, --span
Display months spanning the date.
-s, --sunday
Display Sunday as the first day of the week.
-m, --monday
Display Monday as the first day of the week.
who Command:
The who command is used to get information about currently logged in user on to
system.
Syntax
$who [OPTION]... [ FILE | ARG1 ARG2 ]

-b, --boot--time of last system boot


-d, --dead--print dead processes
-H, --heading--print line of column headings
-q, --count--all login names and number of users logged on
-u, --users--list users logged in

Change Password (passwd) Command:


The password command, passwd, is used to change your password. It has no options
or attributes but rather does its work through a dialog of questions and answers.

Syntax :
$ passwd
In general, good passwords:
1. are significantly different from previous passwords
2. have at least six characters
3. are not common words found in a dictionary
4. are not your name, user id, or a combination of them
5. contain special characters or digits when required by the
system administrator

Print Message (echo) Command:


The echo command copies its arguments back to the terminal.
Syntax
$echo [-options] [ argument]

Echo the STRING(s) to standard output.

-n do not output the trailing newline

-e enable interpretation of backslash escapes

-E disable interpretation of backslash escapes (default)

Documentation(man) Command:
One of the most important UNIX commands is man. The man command displays
online documentation. When you can't remember exactly what the options are for a
command, you can quickly check the online manual and look up the answer. There is even a
manual explanation for the man command itself.

Syntax
$ man [-options] CommandName

-C file, --config-file=file
Use this user configuration file rather than the default of ~/.manpath.
-d, --debug
Print debugging information.
-D, --default
This option is normally issued as the very first option and resets man's be‐
haviour to its default.
-f, --whatis
Equivalent to whatis. Display a short description from the manual page,

Clear Screen (clear) Command


The clear command clears the screen and puts cursor at the top.It is available in most
systems.
Syntax: $clear

System Name (uname) Command:


Each UNIX system stores data, such as its name, about itself. To see thes use the
uname command. We can display all of the data using the all option (-a) or we can speci
name (-n), operating system (default or -s), or software release (-r).
Syntax: $uname [-options]
-a, --all
print all information, in the following order, except omit -p and -i if
un‐known:
-s, --kernel-name
print the kernel name
-n, --nodename
print the network node hostname
-r, --kernel-release
print the kernel release
-v, --kernel-version
print the kernel version

-m, --machine
print the machine hardware name
-p, --processor
print the processor type (non-portable)
-i, --hardware-platform
print the hardware platform (non-portable)

Calculator(bc) Command:
The be command is one of the most interesting commands in UNIX. It turns UNIX
into a calculator. However, it is much more than just a calculator. In many respects, it is
actually a language, similar to C, with a powerful math library ready at your finger- tips.
Syntax:
$bc [options] [arguments]
To start the calculator, we simply key the bc command. To terminate it, we key end of
file(ctrl+d).

Keyboard Shortcuts:

Keyboard Shortcut Task


CTRL+L Clears the screen
CTRL+D Exits the current shell
CTRL+Z Puts the current process into suspended background
CTRL+C Kills the current process
CTRL+H Works the same as backspace
CTRL+A Goes to the beginning of the line
CTRL+W Deletes the word before the cursor
CTRL+U Deletes from beginning of line to cursor position
CTRL+E Goes to the end of the line

File Systems:
In UNIX, a file is any source from which data can be read or any destination to which
data can be written. Therefore, the keyboard, a source of input, is a file; the monitor, a
destination for output.
Filenames:
There are very few restrictions on how you make up filenames in UNIX. Some
implementations limit the length of a filename to 14 characters. Others have names as long as
255 characters.
A filename can be any sequence of ASCII characters. However, we recommend that you not
use some characters in a filename. For example, the greater than (>) and less than (<)
characters cannot be used in a filename because they are used for file redirection.

To make your names as meaningful as possible, we recommend that you use the following
simple rules:

1. Start your names with an alphabetic character.


2. Use dividers to separate parts of the name. Good dividers are the underscore,
period, and the hyphen.
3. Use an extension at the end of the filename, even though UNIX doesn't
recognize extensions. Some applications, such as compilers require file
extensions. In addition, file extensions help you classify files so that they can
be easily identified. A few common extensions are .txt for text files, .dat for
data.
4. Never start a filename with a period. Filenames that start with a period are
hidden files in UNIX.
Generally, hidden files are created and used by the system. They will not be seen when you
list your files. A filename that starts with a period is a hidden file, generally used by a UNIX
utility.

Wildcards
Each filename must be unique. At the same time, we often need work with a group of
files. For example, we may want to copy or list all files belonging to a project. We can group
files together using wildcards that identify portions of filenames that are different. A wildcard
is a token that specifies that one or more different characters can be used to satisfy a specific
request. In other words, wildcards are like blanks that can be filled in by any character.

There are three wildcards in UNIX: the single character (?) wildcard, the set ([...]) wildcard,
and the multiple character (*) wildcard.

 A question mark(?) is replaced by any single character (so h?p matches hop and hip,


but not help).
 Square brackets can surround a choice of characters you’d like to match. Any one of
the characters between the brackets will be matched. For example, [Cc]hapter would
match either Chapter or chapter, but [ch]apter would match either capter or hapter.
Use a hyphen (-) to separate a range of consecutive characters. For example, chap[13]
would match chap1, chap2, or chap3.
 An asterisk is replaced by any number of characters in a filename. For
example, ae* would match aegis, aerie, aeon, etc. if those files were in the same
directory. You can use this to save typing for a single filename (for
example, al* for alphabet.txt) or to name many files at once (as in ae*)
.
File System Organization
Unix file system is a logical method of organizing and storing large amounts of
information in a way that makes it easy to manage. A file is a smallest unit in which the
information is stored. Unix file system has several important features. All data in Unix is
organized into files. All files are organized into directories. These directories are organized
into a tree-like structure called the file system.
Files in Unix System are organized into multi-level hierarchy structure known as a
directory tree. At the very top of the file system is a directory called “root” which is
represented by a “/”. All other files are “descendants” of root.

Directories or Files and their description –


 / : The slash / character alone denotes the root of the filesystem tree.
 /bin : Stands for “binaries” and contains certain fundamental utilities, such as ls
or cp, which are generally needed by all users.
 /boot : Contains all the files that are required for successful booting process.
 /dev : Stands for “devices”. Contains file representations of peripheral devices
and pseudo-devices.
 /etc : Contains system-wide configuration files and system databases. Originally
also contained “dangerous maintenance utilities” such as init,but these have
typically been moved to /sbin or elsewhere.
 /home : Contains the home directories for the users.
 /lib : Contains system libraries, and some critical files such as kernel modules or
device drivers.
 /media : Default mount point for removable devices, such as USB sticks, media
players, etc.
 /mnt : Stands for “mount”. Contains filesystem mount points. These are used,
for example, if the system uses multiple hard disks or hard disk partitions. It is
also often used for remote (network) filesystems, CD-ROM/DVD drives, and so
on.
 /proc : procfs virtual filesystem showing information about processes as files.
 /root : The home directory for the superuser “root” – that is, the system
administrator. This account’s home directory is usually on the initial filesystem,
and hence not in /home (which may be a mount point for another filesystem) in
case specific maintenance needs to be performed, during which other filesystems
are not available. Such a case could occur, for example, if a hard disk drive
suffers physical failures and cannot be properly mounted.
 /tmp : A place for temporary files. Many systems clear this directory upon
startup; it might have tmpfs mounted atop it, in which case its contents do not
survive a reboot, or it might be explicitly cleared by a start up script at boot
time.
 /usr : Originally the directory holding user home directories, its use has
changed. It now holds executables, libraries, and shared resources that are not
system critical, like the X Window System, KDE, Perl, etc. However, on some
Unix systems, some user accounts may still have a home directory that is a
direct subdirectory of /usr, such as the default as in Minix. (on modern systems,
these user accounts are often related to server or system use, and not directly
used by a person).
 /usr/bin : This directory stores all binary programs distributed with the
operating system not residing in /bin, /sbin or (rarely) /etc.
 /usr/include : Stores the development headers used throughout the system.
Header files are mostly used by the #include directive in C/C++ programming
language.
 /usr/lib : Stores the required libraries and data files for programs stored
within /usr or elsewhere.
 /var : A short for “variable.” A place for files that may change often – especially
in size, for example e-mail sent to users on the system, or process-ID lock files.
 /var/log : Contains system log files.
 /var/mail : The place where all the incoming mails are stored. Users (other than
root) can access their own mail only. Often, this directory is a symbolic link
to /var/spool/mail.
 /var/spool : Spool directory. Contains print jobs, mail spools and other queued
tasks.
 /var/tmp : A place for temporary files which should be preserved between
system reboots.

File Types:

In Unix operating system, all data is organized into files. Each file is organized into
directories, and these directories are organized in a tree-like structure called a file system.

The following are the types of files in Unix:

1. Ordinary Files
2. Directories
3. Special Files
4. Pipes
5. Sockets
6. Symbolic Links
1. Ordinary Files

Ordinary files are the files in Unix, which includes program instructions, text, and data.

 In ordinary files, there are no other files.


 Ordinary files are always placed under the directory file.
 Ordinary files are used to store our information like the text which we have to write or
a picture which we have to draw. This is the kind of the file which we mainly work
with.
 In the long-format output of ls -l, the "-" symbol is used to specified such kind of file.

2. Directory

Directory store both special as well as ordinary files. For the users who are familiar with
Mac or Windows operating systems, Unix directories are equivalent to the folders. A
directory file includes an entry file for each file and a subdirectory which it houses. If there
are 5 files in a directory, then there will be 5 entries in the directory. Every entry comprises of
2 components.

I. The name of the File.

II. An inode number, which is a unique identification number for the file or directory.

 We use it to organize the collection of files.


 It contains special files, ordinary files or other directories.
 It does not contain "real" information that we would work with, like text. Mostly, only
need for organizing files.
 Each file is descendant of the root directory (named /) located at the tree's top.

In the long-format output of ls -l, we used the "d" symbol in order to specify this kind of file.

3. Special Files
We use special files to represent the real physical device like terminal, tape drive, and
printer. and also used for Input/Output(I/O) operations. Special files or devices are used
for Input/Output(I/O) on Linux and Unix systems. They look as similar to the ordinary
file or directory in a file system.
Mainly two kinds of special files for every device in the Unix system are there such as
block special files and character special files.
o If we use the block special file for the device input/output (I/O), the data is moved to
the higher fixed-size blocks. This kind of access is known as block device access.

This is one character at a time for the terminal devices. However, for disk devices, raw access
means reading or writing across an entire section of data-blocks that are native to our disk.

o In the long-format output of ls -l, using the "c" symbol character distinct, files are
marked.
o In the long-format output of ls -l, using the "b" symbol block, distinct files are
marked.

4. Pipes
In Unix, with the help of pipes, we can link command together. Pipes is like a
temporary file that only exists to hold the data from one command till it is read by
another. A one-way flow of data is provided by the Unix pipe. The first command's
output sequence is used like an input to the next command sequence. In order to create a
pipe, the vertical bar (|) has to be placed on the command line between 2 commands. Such
as who | wc -l

In the long-format output of ls -l, known as pipes, are marked using the symbol "p."

5. Sockets
Unix sockets are a type of file that enables for advanced inter-process
communication. It is also known as inter-process communication socket. In the
framework of the client-server application, a Unix Socket is used. It is essentially a
data stream, same as the network stream and network socket, except each transaction
is local to the file system.

In the long-format output of ls -l, using the "s" symbol, Unix sockets are marked.

6. Symbolic Link
The symbolic link is used to reference another file in the file system. In order
to reference another file of the file system, we use the symbolic link. It involves a text
representation of the path to the file it refers to. To an end-user, a symbolic link will
seem to have its own name, yet when we need writing or reading data to this file, it
will rather reference these tasks to the file it focuses to. When we delete the soft link
itself, then the data file would, in any case, be there. The symbolic file will not
function if the source file is deleted or moved to the different location.

In the case of the long-format output of ls -l, using the "l" symbol, the symbolic link is
marked.

File System Implementation


In UNIX, a file system has four structural sections known as blocks; the boot block
the super block, the inode block, and the data block. The boot block, super block, inode
blocks are fixed at the beginning of the disk. They occupy the same locations on the disk
even when the disk is reorganized.

Boot Block Inode Block

Super Block
Data Block
A Disk File Format

Boot Block
When an operating system is started, a small program known as the boot programs
used to load the kernel into memory. The boot program, when present, is found at the
beginning of a disk in the boot block.
Super Block
The next block on the disk, the super block, contains information about the file
system. Stored here are such items as the total size of the disk, how many blocks are empty,
and the location of bad blocks on the disk.
Inode Block
Following the super block is the inode (information node) block, which contains
information about each file in the data block. The file information is stored in records known
as inodes. There is one inode for each file on the disk. They contain information about the
file, most notably the owner of the file, its file type, permissions, and address.

Data Blocks
The data block contains several types of files. First and foremost, from the user's point
of view, it contains all of the user files; it is where data are stored. It also contains the special
files that are related to user data: regular files, directory files, symbolic link files, and FIFO
files. Finally, it contains the character special, block special. And socket system files.
Directories:
Like other operating systems, UNIX has a provision for organizing files by grouping
them into directories. A directory performs the same function as a folder in filing a cabinet. It
organizes related files and subdirectories in one place.
Special Directories
Root Directory (/)
The root directory is the highest level in the hierarchy. It is the root of the whole file
structure; therefore, it does not have a parent directory. In a UNIX environment, the root
directory always has several levels of subdirectories. The root directory belongs to the system
administrator and can be changed by only the system administrator.
Home Directory (~)
We use the home directory when we first log into the system. It contains any files we
create while in it and may contain personal system files such as our profile file and the
command history. Our home directory is also the beginning of our personal
directory structure.
Each user has a home directory. The name of the home directory is the user login id or the
user id.
The abbreviation of a user's home directory is the tilde (~). When we use the tilde, the shell
uses the home directory pathname set for us by the system. When we need to refer to our own
home directory, we can just use the tilde.
$cd ~
Working Directory(.)
The working, or current, directory is the one that we are in at any point in a session.
When we start, the working directory is our home directory. If we have subdirectories, we
will most likely move from our home directory to one or more subdirectories as needed
during a session. When we change directory, our working directory changes automatically.
The parent directory is immediately above the working directory.
The abbreviation for the working directory is a dot (.). While it may seem strange that
we need an abbreviation for the current directory, some UNIX commands (such as find, page
108) require that the pathname for a start directory be specified even when it is the
current directory.
Parent Directory(..)
home directory, its parent is one of the system directories. When we move from our
home directory to a subdirectory, our home directory becomes the parent directory.
The parent of any directory is the directory immediately above it in the directory path
from the root. This means that every directory, except the root directory, has a parent.
$cd ..

Paths and Pathnames


• path: list of directories separated by “/”
Absolute Pathname
• Traces a path from root to a file or a directory
• Always begins with the root (/) directory
Example: /home/turing/ray/unix/assign1.txt
Relative Pathname
• Traces a path from the current directory
• No initial forward slash (/)
• dot (.) refers to current directory
• two dots (..) refers to one level up in directory hierarchy
Example: unix/assign1.txt
Links:
Link - is logical relationship between an inode and a file that relates the name of the
file to its physical location. UNIX defines two types of links hard links and symbolic links.
Hard Links
In a hard link structure, the inode in the directory links the filename directly to the
physical file. While this may sound like an extra level of structure, it provides the basis for
multiple file linking.
Symbolic Link
A symbolic (or soft) link is a structure in which the inode is related to the physical file
through a special file known as a symbolic link

Hard Links Soft Links

It is a copy of the original file that serves It is a short pointer file that links a filename to a
as a pointer to the same file, allowing it pathname. It's nothing more than a shortcut to
to be accessed even if the original file is the original file, much like the Windows OS's
deleted or relocated. shortcut option.

It has a similar inode number to the It has a different inode number.


target file.

It cannot be established outside the file It may be established in the file system.
system.

It is faster. It is slower.

The "ln" command is used to make a The "ln -s" command is used to make a soft link
hard link in Linux. in Linux.

It has an additional name for the original It is different from the original file and is an
file that references to the target file alternative for it, but it does not use inode.
through inode.

It may only link to a file. It may link both to a directory or a file.


It remains valid even if the target file is It becomes invalid when the originating file is
deleted. deleted.

Operations Unique to Directories:


 Locate(pwd)
 List(ls)
 Make(mkdir)
 Change(cd)
 Remove(rmdir)

Locate Directory (pwd) Command


We can determine the location of the current directory in the directory structure. This
is particularly useful after we have navigated through the directory structure and we need to
know where we are.
The command used to determine the current directory is print working directory
(pwd). It has no options and no attributes. When executed, it prints the absolute path- name
for the current directory.

Syntax: $pwd

List Directory (ls) Command


The list (Is) command lists the contents in a directory. Depending on the options used,
it can list files, directories, or subdirectories. If the name of a directory is not pro- vided, it
displays the contents of the working directory.

Syntax $ls [Options] [Pathname]


Options:
-l: long list -c: time-inode date
-d: working directory -n: user/group id's
-R: recursive -p: identify directories
-r: reverse order -t: time sequence
-u: time-last access -1 : print one column
 -i: print inode

$ls -l Long List


The simple list command is good for a quick review of the files in a directory, much more
information is available with the long list.
Field Explanation

1)The first character displays the type of file.


* “-” Normal file * “c” character special file
* “d” Directory file * “b” block special file
* “l” symbolic link file * “p” FIFO file * “s” Socket file
Next 9 lines specifies the permissions. Each group of 3 lines corresponds to permissions. So
first three lines stands for user permissions, next 3 for group and next 3 are for others
permissions. Here r stands for read, w for write and x for execute.
2) Second field specifies the number of links for that file.
3) Third field specifies owner of the file. Here owner is “krishna”.
4) Fourth field specifies the group of the file. Here group “krishna” belongs the file.
5) Fifth field specifies the size of file. Here file size for the file Std_details is 361 bytes.
6) Sixth field specifies the last modified date and time of the file.
7) Seventh Field specifies the name of the file/directory itself.
$ls -i : This command will print the inode number associated with each file and directory.

$ls -a : Hidden files are normally not displayed in a file list. That’s why they are called as
“hidden files”. To display all files including hidden files use option -a. The files are starting
with dot(.) are the hidden files.

$ls -p: on a short list to identify which files are directories and which are ordinary. The -p
option appends each directory name with a slash(/).
Make Directory(mkdir) Command
To create a new directory you use the make directory (mkdir) command. It has two
options.
Syntax: $mkdir [options] [dirname]
Example $mkdir dir1 It will create a directory.

Options: -m: mode


-p: parent
$mkdir -m [permissons] dirname
You can control the permissions for the new directory with the mode (-m) option. If
the mode is not specified, the directory will typically have a mode that includes read and
execute for all three sets (owner, group, other) and write only for the owner.

$mkdir -p dir3/dir33/dir333
The second make directory option, parent (-p), creates a parent directory in the path specified
by the directory name. For example, if we need to create a dir33 directory for the dir3 project,
and within dir33 we want to create a dir333 directory.

Change Directory(cd) Command:


Now that we have multiple directories, we need some way to move among them-that
is, to change our working directory. The change directory (ed) command does exactly that.
There are no options for the change directory command. The pathname can be relative or
absolute; generally, it is relative. If there is no pathname argument, the target is the home
directory.

Syntax: $cd pathname

Remove Directory(rmdir) Command


When a directory is no longer needed, it should be removed. The remove directory
(rmdir) command deletes directories. The rmdir command cannot delete a directory unless it
is empty. If it contains any files, UNIX will return an error message, "Directory not empty."

Syntax: $rmdir dirname(s)


Operations Unique to Regular Files

 Create
 Edit
 Display(more)
 Print(lpr)

Create File
The most common tool to create a text file is a text editor such as vi other utilities,
such as cat, nano, gedit that are useful to create small files. Binary files are created by
application programs written for a specific application and utilities such as the C compiler.

Edit File
UNIX provides several utilities to edit text files. The most common is a basic text
editor such as vi. In addition, there are others such as sed, that provide powerful search and
edit tools. All of the basic edit utilities can create a file, but only some can edit one.

Display File (more) Command


Although many utilities write their output to standard output (the monitor), the most
useful one to display a file is more. It allows us to set the output page size and at the end of
each page to allow us to read the file. After each page, we may request one or more lines, a
new page, or quit.

The most basic use of more uses no options. In this basic form, more starts at the beginning
of the file. If the file is small (that is, less than one screen's worth of lines), it prints all of the
data and an "end" message. To return to the command line, key enter.

Syntax: $more [options] input files

Optio Explanation
n
-c Clears screen before displaying
-d Displays error messages.
-f Does not screen wrap long lines.
-l Ignores form feed characters.
-r Displays control characters in format ^C.
-s Squeezes multiple blank lines (leaving only one blank line in output).
-u Suppresses text underlining.
-w Waits at end of output for user to enter any key to continue.
-lines Sets the number of lines in a screen (default is screen size-2).
+nmbr Starts output at the indicated line number (nmbr).

After the text has been displayed, we must enter a command to get more going again. The
two most common commands are space to display the next screen of output and return to
display one more line. If we are done and don't need to see any more output, we enter the
quit (q) command.

Print File
The most common print utility is line printer (lpr). The line printer utility prints the
comments of the specified files to either the default printer or to a specified printer. Multiple
files can be printed with the same command. If no file is specified, the input comes from the
standard input, which is usually a keyboard unless it has been redirected.

Operations Common to Both(Files and Directories)

 Copy(cp)
 Move(mv)
 Rename(mv)
 Link(ln)
 Remove(rm)
 Find(find)

Copy(cp) Command
The copy (cp) utility creates a duplicate of a file, a set of files, or a directory. If the
source is a file, the new file contains an exact copy of the data in the source file. If the source
is a directory, all of the files in the directory are copied to the destination, which must be a
directory. If the destination file already exists, its contents are replaced by the source file
contents. The cp command copies both text and binary files.

Syntax: $ cp [options] sources destination

Options: -p: preserve time and permissions


-i: interactive prompt
-r: recursive copy subdirectories

To copy a file successfully, several rules must be followed:

 The source must exist. Otherwise, UNIX prints the following error message:
<source>- No such file or directory
 If no destination path is specified. UNIX assumes the destination is the current
directory.
 If the destination file does not exist, it is created; if it does exist, it is replaced.
 If the source is multiple files or a directory, the destination must be a directory.
 If the destination is the same directory as the source, the destination filename must be
different. To prevent an automatic replacement of the destination file, use the
interactive(-i) option. When interactive is specified, UNIX issues a warning message
and waits for a reply. Any reply other than yes will cancel the copy of the specific
file. Note, however, that if the file/destination directory is write protected, you cannot
use this option to write to the directory.
 To preserve the modification times and file access permissions, use the preserve
option (-p). In the absence of the preserve options, the time will be the time the file
was copied, and the file access permissions will be the defaults.

Examples:
1.Copy one file in the working directory to the same directory
.

2.To copy a file in one directory to another directory from home directory.

cp Command Options

The copy command has three options: preserve attributes, interactive, and recursion.

Preserve Attributes Option


As stated in the Copy (cp) Command section, when the destination file exists, its
permissions, owner, and group are used rather than the source file attributes. We can force the
permissions, owner, and group to be changed, however, by using preserve (-p) option.
Recursive Copy.
Another way we can copy a collection of files is with the recursive (-r) copy. While
the wildcard copy copies the matching files in a directory, the recursive copy copies the
whole directory and all of its subdirectories to a new directory.

Wildcard copies:
Wildcards can be used to copy files as long as the destination is another directory.
You cannot use wildcards if you are copying to and from the same directory.

Move(mv) Command
The move (mv) command is used to move either an individual file, a list of files, or a
directory After a move, the old file name is gone and the new file name is found at the
destination. This is the difference between a move and a copy. After a copy, the file is
physically duplicated; it exists in two places.

Syntax: $mv [options] sources destination

The first argument is the name of the file to be moved. The second argument is its destination
or, in the case of a rename, its new name.

Options: -i: interactive


-f: force
Example:
Rename(mv) Command
UNIX does not have a specific rename command. Recall that the move (mv) command
with a new name (second argument) renames the file. If the destination file is in the same
directory as the source file, the effect is a renaming the file.

Link(ln) Command
The link command receives either a file or directory as input ,and its output is an updated
directory.
Syntax: $ln [options] sources destination

Options: -s : symbolic
-i: interactive
-f: force
Hard Links
To create a hard link to a file, we specify the source file and the destination file. If the
destination file doesn't exist, it is created. If it exists, it is fin removed and then re-created
as a linked file.

Symbolic Link
When the link (ln) command is executed with no options, the result is a hard link. If we
try to create a hard link to a different file system, however, it is rejected because hard links
must be made within the current directory structure. To link to a different file system,
therefore, we must use symbolic links. We must also use symbolic links when we are
linking to directories.
Syntax: $ln -s sources destination
Remove(rm) Command
The remove (rm) utility deletes an entry from a directory by destroying its link to the
file. Remember, however, that there can be multiple links to a physical file. This means that a
remove does not always physically delete a file. The file is deleted only if, after the remove,
there are no more links to it.

Syntax: $ rm [options] filelist

Options: -f: force


-i: interactive
-r: recursive
To delete a file, we must have write permission. If we try to remove a file that does not have
write permission, UNIX asks for confirmation.

The recursive removal (-r) removes all files and empty directories in the path from the source
directory. Files are deleted first, then the directory, so a directory can have files before the
remove command. A directory is considered empty if all files are deleted.

Find File(find) Command


Given a large file environment, it can quickly become difficult to find a given file. It
not surprising, therefore, that almost all operating systems provide a file search com mand. In
UNIX, it is find. Find has no options. Its first argument is the path that we want to search,
usually from our home directory. The second argument is the criteria that find needs to
complete its search.

Syntax: $find [options] pathname criteria


Complete List of Find Criteria

Criteria Matches..
-name file File name
-perm nnn permissions to nnn, nnn must be an octal number.
-perm-nnn permissions to bit mask, nnn. If bit mask contains 1. permission matches if
it is on.
-type c file type. Valid file types are: block (b), character (c), directory (d), link
(1).
-link n pipe (p). file (f), socket (s)
-user uname number of links for a file
-nouser user name. Numeric user id can also be used.
-group no name in the /etc/passwd file
gname group name
-nogroup no group name in the /etc/group file

Security and Permissions


Users and Groups
In UNIX, everyone who logs on to the system is called a user. Users are
known to the system by their user-ids. In UNIX, however, not every user is created equal.
Some users have more capabilities than others. These users are known as superusers. Also
known as system administrators, superusers have the maximum set of capabilities in the
system; they can even change the system itself. As you might well imagine, super- users need
to have a lot of experience and a lot of training.Users can be organized into groups. A team
working on a project.
UNIX provide a command, groups, to determine a user’s group

Security Levels
There are three levels of security in UNIX: system, directory, and file. The
system is controlled by the system administrator, a superuser. The directory and file securities
controlled by the users who own them.
System Security
System security controls who is allowed to access the system. It begins
with your login id and password. When the system administrator opens an
account for you, he or she creates an entry in the system password file.
Permission Codes
Both the directory and file security levels use a set of permission codes to
determine who can access and manipulate a directory or file. The permission codes are
divided into three sets of codes. The first set contains the permissions of the owner of the
directory or file. The second set contains the group permissions for members in a group as
identified by the group id. The third set contains the permissions for everyone else that is,
the general public.
The code for each set is a triplet representing read (r), write (w), and
execute (x). Read indicates that a person in that category may read a file or directory.
Likewise, write permission indicates that the user can change the file or directory. The last p
mission, execute, has different meanings for directories and files. For a file, it indicates that
the file is a program or script that can be executed. When it is a directory execute permission
allows access to directory.

Summary of Permission Rules:

Permission Read(r) Write(w) Execute(x)


Directory Read contents of Add or delete Reference or move to
Directory entries(files) in directory directory
using commands

File Level Read or Copy files Change or delete files Run executable files
in directory
Changing Permissions
When a directory or a file is created, the system automatically assigns
default permissions. The owner of the directory or file can change them. To change the
permissions, we use the chmod.

Syntax: $chmod [options] mode file/directory


There are two ways to change the permissions: symbolic and octal

Symbolic Codes
There are three sets of operators. To assign absolute permissions to a set, we use the
assignment operator (=). In this case, the current permissions for a set are replaced by the new
permissions. To change only one or two of the permissions in a set and leave the others as
they are currently set, we use a plus sign (+) to add per- missions. To remove one or two
permissions and leave the others alone, we use a minus sign (-).
r-----read
w----write
x----execute

NOTE:
The use of symbolic code in the chmod command allows user to set, add, or remove
individual permissions

Octal Codes
A faster way to enter permissions is to use the octal equivalent of the codes. You must
realize, however, that when using the octal codes, all the permission codes are changed. It is
not like the symbolic modes where you need to specify only what you Want to change. With
octal codes, you must completely represent all of the user codes each time.
In an octal digit, there are three-bit positions. The three different permissions for each
set of codes correspond to the three different bit positions in an octal digit. The first bit
represents the read permission, the second bit represents the write permission, and the third
bit represents the execute permission.

4--------read
2-------- write
1---------execute
Note:
The use of octal code in the chmod command requires that all permissions be
completely reset: a user can not set, add, or remove individual permissions

Changing Owners and Groups: While creating an account on Unix, it assigns a owner ID
and a group ID to each user. All the permissions mentioned above are also assigned based on
Owner and Groups. Two commands are available to change the owner and the group of files:
1. chown: The chown command stands for "change owner" and is used to change the
owner of a file.
2. chgrp: The chgrp command stands for "change group" and is used to change the
group of a file.

Changing Ownership: The chown command changes the ownership of a file. The basic
syntax is as follows: $ chown user file list The value of user can be either the name of a user
on the system or the user id (uid) of a user on the system.
Following example: $ chown amrood testfile
Changing Group Ownership: The chrgp command changes the group ownership of a file.
The basic syntax is as follows:
$ chgrp group filelist
Redirection:
It is the process by which we specify that a file is to be used in place of
one of the standard files. With input files, we call it input redirection; with output
files, we call it as output redirection; and with error file, we call it as error
redirection.
Redirecting Input: we can redirect the standard input from the keyboard
to any text file. The input redirection operator is the less than character (<). Think
of it as an arrow pointing to a command, meaning that the command is to get its
input from the designated file. There are two ways to redirect the input as shown
below:

command 0< file1 or command < file1

The first method explicitly specifies that the redirection is applied to standard
input by coding the 0 descriptor. The second method omits the descriptor. Because
there is only-one standard input, we can omit it. Also note that there is no space
between the descriptor and the redirection symbol.

Redirecting Output:
When we redirect standard output, the commands output is copied to a file
rather than displayed on the monitor. The concept of redirected output appears as
below:

command 1> file1 or command > file1


command 1>| file1 or command >| file1
command 1>> file1 or command >> file1

There are two basic redirection operators for standard output. Both start
with the greater than character (>). Think of the greater than character as an arrow
pointing away from the command and to the file that is to receive the output.

Which of the operators you use depends on how you want to output the file
handled. If you want the file to contain only the output from this execution of the
command, you use one greater than token (>). In this case when you redirect the
output to a file that does not exist, UNIX creates it and writes the output.

If the file already exists the action depends on the setting of a UNIX option
known as noclobber. When the noclobber option is turned on, it prevents
redirected output from destroying an existing file. In this case you get an error
message which is as given in below example.
ksh: whoOct2: file already exists
If you want to override the option and replace the current file’s contents with
new output, you must use the redirection override operator, greater than bar (>|). In
this case, UNIX first empties the file and then writes the new output to the file. The
redirection override output is as shown in the below example:

$ who > whoOct2


$ more whoOct2
abu52408 ttyq3 Oct 2 15:24 (atc2west-171.atc.fhda.edu)
On the other hand if you want to append the output to the file, the redirection
token is two greater than characters (>>). Think of the first greater than as saying you
want to redirect the output and the second one as saying that you want to go to the end
of the file before you start outputting.
When you append output, if the file doesn’t exist, UNIX creates it and writes the
output.
If it is already exists, however, UNIX moves to the end of the file before writing any
new output.

Redirecting errors:
One of the difficulties with the standard error stream is that it is, by default,
combined with the standard output stream on the monitor. In the following example
we use the long list(ls) command to display the permissions of two files. If both are
valid, one displays after the other. If only one is valid, it is displayed but ls display an
error message for the other one on the same monitor.

$ ls –l file1 noFile
Cannot access noFile: No such file or directory
-rw-r- - r- - 1 gilberg staff 1234 Oct 2 18:16 file1

We can redirect the standard output to a file and leave the standard error
file assigned to the monitor.

REDIRECTING TO DIFFERENT FILES:


To redirect to different files, we must use the stream descriptors. Actually
when we use only one greater than sign, the system assumes that we are redirecting
the output (descriptor 1). To redirect them both, therefore, we specify the
descriptor (0, 1, or 2) and then the redirection operator as shown in below
example:

$ ls –l file noFile 1> myStdOut 2> myStdErr


more myStdOut
-rw-r- - r- - 1 gilberg staff 1234 Oct 2 18:16file1
$ more myStdErr
Cannot open noFile: No such file or directory
The descriptor and the redirection operator must be written as consecutive
characters; there can be no space between them. It makes no difference which one
you specify first.

REDIRECTING TO ONE FILE:


If we want both outputs to be written to the same file, we cannot simply
specify the file name twice. If we do, the command fails because the file is already
open. This is the case as given in the following example:

$ ls –l file1 noFile 1> myStdOut 2> myStdOut


ksh: myStdOut: file already exists

If we use redirection override operator, the output file contains only the
results of the last command output which is as given below:

$ ls –l file1 noFile 1>| myStdOut 2>| myStdOut


$ ls myStdOut
Cannot open file noFile: No such file or directory

To write all output to the same file, we must tell UNIX that the second file
is really the same as the first. We do this with another operator called and operator
(&). An example of the substitution operator is shown as follows:

$ ls –l file1 noFile 1> myStdOut 2>& 1


$ more myStdOut
Cannot open file noFile: No such file or directory
-rw-r- - r- - 1 gilberg staff 1234 Oct 2 18:16 file1

JOB CONTROL:

One of the important features of a shell is job control.


Jobs:

In general a job is a user task run on the computer. Editing, sorting and
reading mail are all examples of jobs. However UNIX has a specific definition of a
job. A job is a command or set of commands entered on one command line. For
example:

$ ls
$ ls | lpr

Both are jobs.

Foreground and Background Jobs:


Because UNIX is a multitasking operating system, we can run more than
one job at a time. However we start a job in the foreground, the standard input and
output are locked. They are available exclusively to the current job until it
completes. This means only one job that needs these files can run at a time. To
allow multiple jobs, therefore, UNIX defines two types of jobs: foreground and
background.

FOREGROUND JOBS:
A foreground job is any job run under the active supervision of the user. It
is started by the user and may interact with the user through standard input and
output. While it is running, no other jobs may be started. To start a foreground job,
we simply enter a command and key Return. Keying Return at the end of the
command starts it in the foreground.
Suspending a foreground job While a foreground job is running it can be suspended.
For example, while you are running a long sort in the foreground, you get a notice that
you have mail.
To read and respond to your mail, you must suspend the job. After you are through
the mail you can then restart the sort. To suspend the foreground job, key ctrl+z. To resume
it, use the foreground command (fg)

Terminating a foreground job If for any reason we want to terminate (kill) a running
foreground job, we use the cancel meta-character, ctrl+c. After the job is terminated, we key
Return to activate the command line prompt. If the job has been suspended, it must first be
resumed using the foreground command.

BACKGROUND JOBS:

When we know a job will take a long time, we may want to run it in the background. Jobs
run in the background free the keyboard and monitor so that we may use them for other tasks
like editing files and sending mail.

Note: Foreground and Background jobs share the keyboard and monitor.

Any messages send to the monitor by the background job will therefore be
mingled with the messages from foreground job.

Suspending, Restarting and Terminating Background jobs To suspend


the background job, we use the stop command. To restart it, we use the bg
command. To terminate the background job, we use the kill command. All three
commands require the job number, prefaced with a percent sign (%).

Example:
$ longjob.scr&
[1] 1795841
$ stop %1
[1] + 1795841 stopped (SIGSTOP) longjob.scr&
$ bg %1
[1] longjob.scr&
$ kill %1
[1] + Terminated longjob.scr&

Moving between Background and Foreground To move a job between


the foreground and background, the job must be suspended. Once the job is
suspended, we can move it from the suspended state to the background with the bg
command. Because job is in the foreground, no job number is required. To move a
background job to a foreground job, we use the fg command.

You might also like