Linux Full Modules
Linux Full Modules
Linux Full Modules
Linux community help: as Linux is a community product, it has very active system and
24*7 community help for any query related to Linux.
User friendly desktop effects: in the past three years, companies supplying Linux have
stressed heavily on their desktop versions and now it is better than any other OS for home
and office use.
Easy upgrade: Linux gets upgraded through its package manager, and the same goes for its
other applications. Its upgradation feature makes it unique and handy as compared to other
proprietary software.
Highly customizable: customization is strength of Linux and it is because of this very
feature that it is becoming the first choice for any professional.
Experience live: it is another unique feature developed by most Linux companies to provide
a live environment for use. Now Linux is PC independent and you can use it from any
system, anywhere in the world.
Multi-user environment: Linux provides the real multi-user environment, which means
Linux system can support different users with different privileges. In Linux system, each user
has access to a predefined set of system services and their own private data. The private data
in turn can be shared with other users by granting access privilege to them. All the privilege
checking is done with the help of user accounts maintained by the system. This is a unique
Multiprogramming:
feature of Linux, whichAllows
providemany
extra programs
security. to be executed simultaneously by different
users.
Time-sharing: Is a concept that allows multiple programs to share CPU time for their
execution. The programs are placed in a sequence before their execution. Each program gets
CPU time for a specific time period. In that specific time period, the program is executed.
After the specified time period for program execution is expired, the program is put back in
the sequence to wait its turn again. The next program in the sequence is allotted the CPU
Multitasking: Is a concept that enables execution of multiple tasks simultaneously. A
time for its execution.
process in Linux is broken down into tasks. At a time,' each task either reads data from or
writes data to the disk, or waits for input from a user. When a task is waiting for the
completion of an activity, such as getting input from the keyboard, the CPU, instead of
wasting time, starts executing the next task. Therefore, while one task is waiting for input
Virtual
from thememory: Helps
user, another optimize
program thebe
could useinof
theresources,
process ofsuch as read
being memory
from and CPUdisk.
the hard time. The
physical memory may not always be sufficient for executing large applications or activating
multiple applications at a particular point of time. In such situations, Linux makes a portion
of the hard disk, called swap partition, available for use as the virtual memory. The computer
SJAHER,MOOLAMATTOM
keeps the programs and data that are not frequently required on the swapSigma Sathyan
partition and loads
4
them in the physical memory, whenever required. Therefore, it uses the resources of the
computer to the optimum.
Shared libraries: Are a set of functions that are needed by applications to execute programs.
The use of shared libraries helps to save hard disk space and memory because you do not
need to write the code separately for each application. You can create the functions and put
them in the shared libraries so that all applications can use these functions.
Samba: Is a suite of programs that implement the Server Message Block (SMB) protocol in
Linux that helps share a file created on Linux with the Windows operating system. SMB is
the protocol used by the Microsoft operating systems to share file and print services. SMB
also enables the sharing of printers connected to either Linux or the Windows OS.
Network Information Service (NIS): Is a client and server database system that helps share
passwords and group files across the Linux network. NIS server also maintains a central
database of account information that is used for account authentication.
Cron scheduler: Is a scheduler program that is used to run commands, scripts, or programs
at scheduled times.
Office suite: Is a package that supports OpenOffice.org, which is an application program
with several built-in tools. OpenOffice.org helps create documents, spreadsheets, and
presentations.
Data archiving utilities: Are a set of utilities used for data backup. The different data
archiving utilities are: tar, cpio, and dd. Advanced Maryland Automatic Network Disk
Archiver or Amanda is a backup system supported by Linux that uses data archiving utilities.
It enables the LAN administrator in setting up a master backup server and makes back up for
multiple hosts in a large capacity tape drive.
Web server: Is the software that hosts Web pages. Linux comes with the Apache Web
server, which is the most popular Web server in use today.
Licensing: Linux is licensed under the GNU General Public License. This license states that
anyone who wants to use and apply it can do so, and has the right to change linux and
eventually redistribute the changed version, with one condition that the code should be
available after redistribution.ie, you are always free to grab a kernel image for any of your
functions as long as your client can still have a copy of that code.
*Since it is mostly written in C language, it is flexible & portable.
*It provides multilevel file system. The linux file structure is set up according to FHS (File
Hierarchy standard)
Linux is free: When we say Linux is free it does not mean it is free of cost; it means Linux is
free to adopt. You can always download Linux from the Internet absolutely for free. There is
no registration fee, no costs for using it and you will still get free updates. The most unique
feature is its freely available source code which you can customize according to your
requirements.
The license commonly used in the GNU Public License(GPL). This license states that anyone
who wants to use and apply it can do so, and has the right to change the Linux and eventually
redistribute the changed version, with one condition that the code should be available after
redistribution. In other words, we can say that you are always free to grab a kernel image for
any of your
Linux functions independent:
is hardware as long as yourThe
client can still have
advantage with aLinux
copy of
is that
that code.
the source code and
documentations are always available. Thus if you find any difficulty in installing Linux in
any hardware, you can easily customize it as per your needs. This makes Linux hardware
independent.
Linux keeps on running: As with UNIX, a Linux system expects to run without rebooting
ever time you can switch on the system. Consequently , there is no boteration of maintaining
standards of performance. This is why many tasks are executed at night or scheduled for
other such calm moments, ensuring higher availability during busier periods and a more
balanced use of the hardware. This property allows Linux to be applicable also in
Linux is secure
environments andpeople
where versatile: Linux for
are pressed hastime.
proven beyond doubt the sound security level it
offers. The security aspect is the key feature of Linux and its security model entirely based on
UNIX, which we all know is very robust and of proven quality. In Linux, security is not only
restricted to, security from Internet threats but is also secure from other system –related
breachesis orscalable:
Linux malpractices.
Linux is created in a way that it is suitable for any application, any
hardware, and any process. From a Palmtop with 2MB of memory to a petabyte storage
cluster with hundreds of nodes, add or remove the appropriate packages and Linux fits all.
• Reliability: Implies the stability of Linux because Linux servers are not shut down for years
together. As a result, using Linux operating system enables you to work consistently with the
Linux server without reporting any operating system failures.
• Backward compatibility: Provides support for the existing hardware. The feature of
providing support for the existing hardware is called backward compatibility.
• Easy upgrade and installation process: Provides menu-driven Installation of Linux. It
also allows you to upgrade from prior versions.
• Low total cost of ownership: Lowers the cost of ownership because most of the packages
that come with it are available free of cost. The system configuration requirements for
installing Linux, such as speed of processor and amount of RAM required are also very
minimal. As a result, the hardware cost goes down.
• Graphical User Interface (GUI): Is a user interface that helps the users to interact with the
computer easily. The GUI of Linux is X Window system. The X Window system consists of
two subsystems: server and client. Linux has a number of GUIs called Desktop
Environments, such as K Desktop Environment (KDE) and GNU Object Model Environment
(GNOME). Both, KDE and GNOME are versions of the X Window system and run on X
•server.
Excellent security features: Offers security because Linux is free of any virus attack. As a
result, there is more security in Linux as compared to other operating systems. This is the
reason why many Internet Service Providers are replacing their current operating systems
with Linux.
• Support for high user load: Supports a large number of users working simultaneously.
That is why it is used in the organizations where the number of users is large.
• Support for application development: Offers an excellent platform for many development
languages, such as C, C++, JAVA, Python, PHP, and Perl. It also supports Integrated
Development Environments, such as KDevelop and Glade.
IDENTIFYING LINUX PRE-REQUISITES (INSTALLING REQUIREMENTS)
There are various hardware requirements as well as software requirements to install
Red Hat Linux 9 on your computer. You need to fulfill these requirements before installing
Red Hat Linux 9. The requirements include availability of Red Hat Linux 9 software. You
can install Red Hat Linux 9 in different ways, such as using Compact Disk-Read Only
Memory (CD-ROM), downloading it from the Internet, from your hard drive or directly
Hardware
through Requirements
File Transfer Protocol (FTP, NFS, HTTP).
Before installing any software, you need to consider the hardware requirements for
that software. The hardware requirements necessary for successful installation of Red Hat
Linux 9 can be classified as follows:
• Requirements related to CPU: The requirements related to CPU:
- Minimum: Pentium-class, such as Pentium I and Pentium II.
- Recommended for text-mode: 200 MHz Pentium-class or higher version
- Recommended for graphical mode: 400 MHz Pentium II or higher version
• Requirements related to hard disk space: Requirements related to hard disk space:
- Custom Installation (minimum): 475MB
SJAHER,MOOLAMATTOM Sigma Sathyan
7
- Server (minimum): 850MB
INSTALLING LINUX
ARCHITECTURE OF LINUX
It was developed at AT & T and named after its developer David Korn. The Korn Shell
combines the features of both the Bourne and C shells. Its executable file name is ksh.
RESTRICTED SHELL
You use the restricted shell to provide limited access on the operating system to a user. The
restricted shell is typically used for guest users who only need limited rights and permissions.
You can use this shell to restrict the users of the operating system to a limited environment.
BASH SHELL
It is an enhancement on the Bourne Shell, hence the name Bash which is an acronym for
Bourne Again Shell. Bash is product of Free Software foundation‘s GNU project. It is the
default shell for most Linux systems stored in the /bin directory. It stores all of the commands
that you use in a session and also in the previous shell. In Red Hat Linux, the sh command is a
symbolic link to bash.
Tcsh SHELL or TC SHELL
Tcsh stands for Tom‘s C shell and is an enhancement of the C shell. It is also known as the
TC shell. In Linux the csh command is a symbolic link to the Tcsh shell. We can execute the
Tcsh shell by typing either csh or tcsh at the command prompt.
A SHELL
It was developed by Kenneth Almquist of the University of Berkeley.It emulates the Bourne
shell. The A shell is suitable for computers that have limited memory. The executable file
name for the A shell is ash.
Z SHELL
It offers the features of Tcsh and Korn shells. It also provides a large number of utilities and
extensive documentation. The executable file name for the Z shell is zsh.
disk may comprise a single file system or it may be partitioned to house several file systems.
But the reverse is not true. No file system can be split over two systems. Ie, it provides a
mechanism trough which we can store and organize files in our hard disk.
The disk space allotted to a Linux file system is made up of ‗blocks‘, each of which is
typically of 512 bytes. Some have block sizes of 1024 or 2048 bytes. The block size depends
upon how the file system is implemented on a particular installation. It amt also change from
one Linux version to another.
To check the block size use the following command:
$ cmchk
BSIZE=1024
All the blocks belonging to the file system are logically divided into four parts. The first block
of a file system is called the 'Boot block' which is followed by 'Super block', 'Inode Table'
and'Data Blocks J Let us understand these blocks one by one.
The Boot Block
This represents the beginning of the file system. It contains a program called 'bootstrap
loader'. This program is executed when we 'boot' the host machine. Although only one boot
block is needed to start up the system, all file systems contain one (possibly empty) boot
block.
The Super Block
The super block describes the state of the file system - how large it is, how many maximum
files it can accommodate, how many more files can be created etc. It contains information
like:
a) Size of the file system
b) Number of free blocks on the system
c) A list of free blocks
d) Index to the next free block on the list
e) Size of the inode list
g)
f) Number and list of free inodes
h)
Index
The Inode to the next free inode on the list
Table
Flags to indicate modification of super block
We know that all entities in UNIX are treated as files. The information related to all these files
(not the contents) is stored in an Inode Table on the disk. For each file, there is an inode entry
in the table. Each entry is made up of64_bytes and contains the relevant details for that file.
These details are:
SJAHER,MOOLAMATTOM Sigma Sathyan
12
(a) Owner of the file
(b) Group to which the owner belongs
(c) Type of file
(d) File access permissions
(e) Date and time of last access
(f) Date and time of last modification
(g) Addresses
(i) Number ofoflinks to the
blocks filethe file is physically present
where
(h) Size of the file
Data Blocks
These contain the actual file contents. An allocated block can belong to only one file in the
file system. This block cannot be used for storing any other file's contents unless the file to
which it originally belonged is deleted.
Surrogate Super Block and Inode Table
Judging by the information stored in the Inode Table this must change whenever we use any
file, or change its permissions, etc. Making these changes on the disk would waste a lot of
precious CPU time. To solve this, a copy of the Super Block and Inode Table gets loaded into
memory (RAM) at start-up time. Since memory access is faster than disk access, less time is
consumed in recording the changes in the RAM copies of Super Block and Inode Table every
time some modification occurs. The original SuperBlock and Inode Table on the disk are
updated after a fixed interval of time; say every 30 seconds, by a command called sync. sync
synchronizes the inode table in memory with the one on disk by simply overwriting the
memory copy on to the STRUCTURE
LINUX DIRECTORY disk. Thus, the changes that may have been recorded in the copy in
In Microsoft
memory Windows
during the last almost
intervalallofprograms areget
30 seconds installed in ―Program
duly registered on theFiles‖.
disk. It doesn‘t happen
in the case of Linux.
/home
Home directory is the parent to the home directories of users.
/lib
Contains library files, including loadable driver modules needed to boot the system.
/media
Directory for mounting files systems on removable media like CD-ROM drives, floppy disks,
and Zip drives.
/mnt
A directory for temporarily mounted File Systems.
/opt
Optional software packages copy/install files here.
/proc
/sbin
A specialadministrative
Contains directory in abinary
virtualfiles.
File System. It contains
Commands such as the information
mount, about
shutdown, various
umount, aspects
reside
of a Linux system.
here.
/root
/srv
Home directory
Contains data for of the root
services user. FTP, etc.) offered by the system.
(HTTP,
/sys
A special directory that contains information about the devices, as seen by the Linux kernel.
/tmp
Temporary directory which can be used as a scratch directory (storage for temporary files).
The contents of this directory are cleared each time the system boots.
/usr
Contains subdirectories for many programs such as the X Window System.
/usr/bin
Contains executable files for many Linux commands. It is not part of the core Linux operating
system.
/usr/include
Contains header files for C and C++ programming languages
/usr/lib
Contains libraries for C and C++ programming languages.
/usr/local
Contains files that are shared, like, default configuration files, images, documentation, etc
Contains local files. It has similar directories as /usr contains.
/usr/src
/usr/sbin
Contains the source code for the Linux kernel.
Contains administrative commands
SJAHER,MOOLAMATTOM Sigma Sathyan
usr/share
15
/var
Contains various system files such as log, mail directories, print spool, etc. which tend to
change in numbers and size over time.
/var/cache
/var/lib
Storage area for cached data for applications.
Contains information relating to the current state of applications. Programs modify this when
they run.
/var/lock
Contains lock files which are checked by applications so that a resource can be used by one
application only.
/var/log
Contains log files for different applications.
/var/mail
Contains users' emails.
/var/opt
Contains variable data for packages stored in /opt directory.
/var/run
Contains data describing the system since it was booted.
/var/spool
A command is an instruction given by a user telling a computer to do something, such a run a
Contains data that
single program or aisgroup
waiting
of for some
linked kind of processing.
programs. Commands are generally issued by typing them
/var/tmp
in at the command line and then pressing the ENTER key, which passes them to the shell.
A command
Contains consists
temporary ofpreserved
files a command namesystem
between usually followed by one or more strings that
reboots.
comprise options and arguments.
Linux Each of these strings is separated by white space .The
Commands
general syntax for commands is
command [options] [arguments]
The square brackets indicate that the enclosed items are optional. Most commands have at
least a few options and can accept (or require) arguments. However, there are some
commands that do not accept arguments, and a very few with no options.
COMMANDS FOR FILE AND DIRECTORIES
cd
The cd command, which stands for "change directory", changes the shell's current working
directory. Type cd followed by the name of a directory to access that directory. General
format is
cd <directory name>
Eg: cd games
If the directory games is not located hierarchically below the current directory, then the
complete path must be written out.
Eg:the
cd current directory
/usr/games
To Eg: cd up
move .. one directory, use the shortcut command. Hence Move to the parent directory of
ls
ls lists the contents of a directory. If no target directory is given, then the contents of the
current working directory are displayed.
General format is
ls [-options] <directory name>
options includes
-a list hidden files
-d list the name of the current directory
-F show directories with a trailing '/ and executable files with a trailing '*'
-g show group ownership of file in long listing
-l long listing giving details about files and directories
-i print the inode number of each file
-R list all subdirectories encountered
-t sort by time modified instead of name
Eg
$ ls
bin dev home mnt share usr var test1.text palindrome.sh
$ ls -l
total 8904
-rw-rw-r-- 1 mca 571 82 Aug 6 2009 12.java
cp
cp is used to make copies of files or entire directories. To copy files, use general format :
where source-file(s) and destination specify the source and destination of the copy
respectively. The behaviour of cp depends on whether the destination is a file or a directory. If
the destination is a file, only one source file is allowed and cp makes a new file
called destination that has the same contents as the source file. If the destination is a directory,
many source files can be specified, each of which will be copied into the destination
directory.
cp myfile yourfile
Copy the files "myfile" to the file "yourfile" in the current working directory. This command
will create the file "yourfile" if it doesn't exist. It will normally overwrite it without warning if
it exists.
cp -i myfile yourfile
With the "-i" option, if the file "yourfile" exists, you will be prompted before it is overwritten.
cp -i /data/myfile
Copy the file "/data/myfile" to the current working directory and name it "myfile". Prompt
before overwriting the file.
cp -dpr srcdir destdir
Copy all files from the directory "srcdir" to the directory "destdir" preserving links (-p option),
file attributes (-p option), and copy recursively (-r option). With these options, a directory and
all it contents can be copied to another dir
rm
$ rm [-options]target-file(s)
removes the specified files. Unlike other operating systems, it is almost impossible to recover
a deleted file unless you have a backup If you would like to be asked before files are deleted,
use the -i option:
$ rm -i myfile
rm: remove 'myfile'?
SJAHER,MOOLAMATTOM Sigma Sathyan
19
‘rm’ can also be used to delete directories (along with all of their contents, including any
subdirectories they contain). To do this, use the -r option. To avoid rm from asking any
questions or giving errors (e.g. if the file doesn't exist) you used the -f (force) option. Extreme
care needs to be taken when using this option - consider what would happen if a system
administrator was trying to delete user will's home directory and accidentally typed:
$ rm -rf / home/will
mkdir
Make directory. Syntax is
makdir [-p] <directory name 1><directory name2>
$ mkdir bcas6
The option –p allows you to create multiple generations of directories at one go.here
–p tells linux to create works, then within it bpb, next its child directory linux and
lastly book nested within all these.
$ mkdir -p works/bpb/linux/book
To create a directory which should have permissions 754 irrespective of the umask
you can use the command:
$ mkdir -m 754 newdir
$ rmdir bcas6
To remove the parent directories of book , we use:
$ rmdir -p works/bpb/linux/book
Here on removing book directory if the linux directory is empty it will be removed
and if the bpb directory falls empty then that too gets removed and so on. This
PWD stops when rmdir bumps into a non empty parent directory.
process
Show the name of the current working directory. The pwd (print working directory) command
will show you the full path to the directory you are currently in.
$ pwd
more /etc/profile
file
file - determine file type.
This command lists the general classification of a specified file. It lets you to know if the
content of the specified file is ASCII text, data, separate executable, empty or others.
General format is file < filename>
$ file test1.txt
test1.txt: ASCII text
$ file *
amitha_linux.sxw: Zip archive data, at least v2.0 to extract
ample.txt: empty
anand: directory
anupama: directory
aswathy: ASCII C program text
bank_challan.pdf: PDF document, version 1.4
bank.java: ASCII Java program text
Bin:
directory
chardemo.class: compiled Java class data, version 46.0
here * indicates the content of the current directory.
more
Displays the contents of target-file(s) on the screen, pausing at the end of each screenful and
asking the user to press a key (useful for long files). It also incorporates a searching facility
(press '/' and then type a phrase that you want to look for).
You can also use more to break up the output of commands that produce more than one
screenful of output as follows
$ more stud_details
Roll_no marks
1 44
2 33
3 45
4 56
--More--(01%)
More command pauses when the screen fills and waits for pressing a spacebar key
before it moves to another screenful of text. A message at the bottom of the screen
tells us the percentage of file that has been displayed so far. We can press Ctrl-C to
quit more command before reaching the end of file.
less
The less command works like more except that it moves both forward and backward
in the file while the command is running. We can use the B key on your keyboard to
back up one screen or a spacebar to move forward and display the next screen.
$ less prime1.c
touch
Touch creates files with zero bytes. Doesn‘t allow storing anything in file.
$ touch sample
To create many empty files quickly
$ touch sample1 sample2 sample3 sample4
To create a new file with some data in it – for example, a line of text we use the echo
This will create a file named firstfile with only one line in it MG UNIVERSITY.
command.
cat
$echo MG UNIVERSITY > firstfile
$ cat target-file(s)
displays the contents of target-file(s) on the screen, one after the other
q
w
e
$ cat file24
1
3
44
head
55
It is used to display the starting lines of a file and also specifies how many line to display. By
default it will display 10 lines.
Synatx: $ head [options] filename
Options
-n specify how many lines you want to display.
-n number the number option argument must be a decimal integer whose sign affects the
location in file measured in lines
-c number the number option argument must be a decimal integer whose sign affects the
location in file measured in bytes
$ mkdir amitha
If more than one file is given with head command, it will return 10 lines from each file.
$ cd amitha
$ cat test1
qwqeqreq
eqrwqrfw
deawqrdfwsfr
dfsf
sf
fsfsfsgv
fgsdgdgbd
gdgdgb
$ head -3 test1
qwqeqreq
eqrwqrfw
$ head -n 6 test1
deawqrdfwsfr
qwqeqreq
$ head -c 4 test1
SJAHER,MOOLAMATTOM Sigma Sathyan
qwqe
25
eqrwqrfw
deawqrdfwsfr
dfsf
sf
fsfsfsgv
$ cat s1
qw
weret
sdf
dsfdgfs
fsfgsg
$ cat s2
qeer
sfdf
rtyr
cbc
$ head -c 2 s1 s2
==> s1 <==
qw
==> s2 <==
qe
$ head -n 4 s1 s2
==>
sfdf s1 <==
qw
rtyr
weret
cbc
sdf
tail
dsfdgfs
==> s2 <==
It is used to display the last or bottom part of the file. By default it will give 10 lines.
qeer
Syntax: $ tail [options] filename
Options
-n specify how many lines you want to display.
-n number the number option argument must be a decimal integer whose sign affects the
location in file measured in lines
-c number the number option argument must be a decimal integer whose sign affects the
location in file measured in bytes
$ tail -2 s1
dsfdgfs
fsfgsg
$ tail -c 2 s1 s2
==> s1 <==
g
==> s2 <==
c
$ tail -n 3 s1 s2
==> s1 <==
sdf
dsfdgfs
fsfgsg
FILE
==> s2COMPARISONS
<==
$sfdf
cat file1
hello
rtyr how r u
what
cbc is ur name
$ cat file3
hello how r u
what ar you doing?
cmp
It is used to compare two files. It reports the first instants of differences between the specified
files.ie, two files are compared byte by byte and the location of the first mismatch is
displayed.
Syntax: cmp <filename1><filename2>
comm
It compares two sorted files line by line.
hello how r u
what is ur name
$ comm -23 file1 file3
what is ur name
$ comm -1 file1 file3
hello how r u
diff
$ diff file1 file3
2c2
< what is ur name
---
DISK RELATED COMMANDS
> what ar you doing?
df – disk free
This command reports the free as well as the used disk space for all file system installed in
your machine.df will give output in KB.
$ df
Filesystem 1K-blocks Used Available Use%
Mounted on
97122640 10076428 82112652 11%
/dev/sda3
SJAHER,MOOLAMATTOM Sigma Sathyan
28
/
none 1018144 0 1018144 0%
/dev/shm
To display the output in human readable format, like MB and GB
$Filesystem
df -h Size Used Avail Use% Mounted on
/dev/sda3 93G 9.7G 79G 11% /
995M 0 995M 0% /dev/shm
none
du – disk usage
It is used to find the size of current directory. It gives the list of directories present in current
directory and their size in KB or MB or GB recursively.By default everything in KB
$ du
964 ./share/locale
544 ./share/icons
48
24 ./share/realplay
./share/superbuffer
1876 ./share
12
220 ./.mozilla/default/ontku2i6.slt/chrome
To get output ./.mozilla/default/ontku2i6.slt
in more clear way use -h
$ du -h
4.0K ./newdir
12K
4.0K ./works/vimal/newdirect
./fas
16K ./works/vimal
4.0K ./works/bpb/unix/book
8.0K ./works/bpb/unix
8.0K
8.0K ./.xemacs
./za
16K ./nebila
If we specify a directory then du descends down this directory locating any sub directories
lying in it and reports the blocks used by the directory and the sub directories.
$ du
0 /dev/dev/mapper
0 /dev/snd
0 /dev/disk/by-path
0 /dev/input
/dev/disk
To get the size of whole directory
0
$ du -s
74732
SJAHER,MOOLAMATTOM Sigma Sathyan
29
$ du -sh
73M
It contains a value which signifies the largest file that can be created by the user in the file
system.
$ ulimit
Unlimited
$ ulimit 1
Here onwards no file can be created whose size is bigger than 512 bytes. Once reduced this
value remains effective till the user doesn‘t log out. This change will be effective only for the
current session and the system will return to its default value when you log out.
An ordinary user can only reduce the ulimit value and is never permitted to increase it. A
super user is an exception to this rule and can increase or decrease this value.
Sigma Sathyan
30
5) Wait state: some processes might be required to do an I/O operation. Since I/O is a slow
operation the cpu cant lie idle till the time I/O is over. So such processes are put in wait state
until their I/O is over and are then placed in the ready state.
6) Complete state: A process whose execution comes to an end goes into complete state and
is then removed from the process queue. (stopped) The process can be stopped by sending a
Types of processes
signal.
1) ZOMBIE: It is a process that has completed execution but still exists in the process table.
Zombie means an undead person. Once a zombie is removed its process ID and entry in the
process table can then be reused.
2) ORPHAN: It refers to a process whose parent process has finished or terminated. A
process can become orphan during the remote invocation when the client process crashes after
making a request of the server. They generally waste server resources and can leave a server
in problem. Any orphaned process can be adopted by the special init system process. This is
called re-parenting.
3) DAEMON: It is a process that is constantly running in the background. They run without
theprocess
A user requesting them
is born the to doitso.stars
moment They are neither
executing and linked
is dead with
oncea ituser nor a terminal.
terminates. These
For a process
processes
to be born are created
another when should
process the system
giveboots
birth up andThe
to it. remain
new active
processuntil the system
is called is halted
the child or
and the
shut down.
process that starts it is called is the parent.
PID- PROCESS IDENTIFICATION NUMBER
PID refers to the process identification number of the process you wish to find the parent.
When a process is started it is assigned a unique and the next available PID. As soon as it
terminates, its PID is released for eventual reuse. PID starts with 0 and runs up to a maximum
of 32767.When a maximum is reached it count from 0 again.
ps command
To view the PID of any process we use ps at the prompt. It shows the following details:
1) The pid
2) The terminal from which the processes were launched
4)
3) Command
Amount of with
time which the process
the process was started.
has used
The output of ps looks like:
$ ps
PID TT STAT TIME COMMAND
6651 P0 S 0:01 -ksh<\n>
SJAHER,MOOLAMATTOM Sigma Sathyan
32
7193 p1 R0:0 ps
The output of ps command shows the many fields. Some of them are:
o USER or UID – Process owner
o PID – Process Identification Number
o %CPU – CPU utiliztion of the process
o %MEM – Percentage of memory in KB used by the process
o
o TTY – Terminal(console)
START associated
– Process start time or date with the process
o
o TIME –– Current
STAT Total CPU time
state usedprocess
of the by the process
o COMMAND – Command being executed
o NI - The nice priority number
o PRI – Process Priority Number
o FLAGS – Numeric flag associated with the process
o PPID – PID of the parent process
Some of the options used with ps command are:
Examples:
To find all processes belonging to user Arjun : $ ps U Arjun
PSTREE COMMAND
The pstree command shows the processes and parent – child relationship. It displays the
running process in tree format.
kill command
Some of the reasons why you would like to terminate a process in the middle of its execution
are given below:
a) The terminal has hung. A typical e.g.: of this is when you attempt to cat a directory file.
b) The program, which is running, has gone in an indefinite loop and hence is not getting
terminated.
c)
ToThe system
carry performance
out killing has gone
a process below
first note theacceptable limits
PID of the because
process of too
to be many
killed processes
using the ps
command
running in and use kill command.
the background.
$ kill 5001
5001 terminated
$ kill –9 3216
The –9 refers to sure 100% killing. The signal number 9 (sure kill) forcibly terminates a
process.
The kill command with –l option shows list of all kill signals.
$ kill –l
SIGHUP – Hang up
SIGINT – Interrupt
SIGTRAP
SIGQUIT –– Trace
Quit Trap
SIGKILL – kill. This signal can‘t be caught, blocked, ignored.
SIGTERM – software termination. This is often sent before a kill signal is sent.
SIGSTOP – stop. This signal can‘t be caught, blocked or ignored.
34
Background Processing
Most of the system processes run in the background, while the user executes their processes in
the foreground. If the user so desires even he can run his processes in the background. The
user can run time-consuming tasks like sorting a huge file and storing the sorted output in a
file in the background. This way he would not be required to wait till the sorting is over to be
able to run the next process. He can immediately concentrate on another task the moment
D
killall command
sorting process is submitted to run in the background.
35
It allows the user to specify a process by name.
To run a process in the background, UNIX provides the ampersand (&) symbol.While
$ killalla Netscape
executing command, if this symbol is placed at the end of the command then the command
will be executed in the; background. When you run a process in the background a number is
displayed on the screen. This number is the PID of the process that you have executed in the
$background.
sort employee.dat > emp.out &
17653
$
The task of sorting the file employee.dat and storing the output in emp.out has now been
assigned to the background, letting the user free to carry out any other task in the foreground.
$ myprogram &
[1] 1364366
nd
The 2 line shows that the background job number is [1],its PID is 1364366, myprogram is
sent to background.
Though the facility to run processes in the background is of great advantage, it comes with a
few limitations too. These are:
a) On termination of a background process no success or failure is reported on the screen.
We can search for the PID in the output of ps to verify whether the process is still running or
has been terminated.
b) The output of a background process should, always be redirected to a file. Otherwise you
would get a garbled screen showing the output of the background process along with whatever
you are doing in the foreground.
c) With too many processes running in the background the overall system performance is
likely to degrade.
next time. If we do not redirect the output of our background process the command acts
intelligently and stores the output in the file ‗nohup.out‘.
$ nohup sort employee.dat &
16779
Sending output to nohup.out
$ FTP Client
Press Ctrl Z to stop the current job. The following command will run the music player
application:
$ xmms
Press Ctrl Z to stop the current job. The following command will compile a c program:
$ gcc Fibonacci.c
Press Ctrl Z to stop the current job. The following command will display the jobs in the shell:
$ jobs
[1] stopped FTP Client
[2] stopped xmms
[3] stopped
The following command gcc
will bring the FTP Client process in the fore by job number 1.
$ fg 1
Changing Process Priorities
Though all processes are equal, some processes are more equal than others. They can be made
so by increasing their priority. The processes with higher priority would obviously get a time
slot earlier and would be fired earlier than the other processes in the queue.
The priority of a process is decided by a number associated with it. This number is called
37
'nice' value of the process. Higher the nice value of a process lower is its priority. The nice
value of a process can range from 0 to 39, with 20 as the default nice value of a process. Thus,
a process with a nice value 25 would execute slower than the one with a nice value 20.
Let's try to increase the nice value of one of our processes.
user 0.0
sys 0.1
Note that in the above command we have redirected the output of ls so that it doesn't mix up
with the output of the time command. The output of time command doesn't get redirected
since the output of the time command is written to the standard error device, i.e. the screen.
The 'real' time in the above output represents the time taken by the command to execute
since its initiation to its termination. The 'user' time represents the amount of time that the
command/program took to execute its own code. For small programs which take milliseconds
to execute, this time is often reported as 0.0, as in the above case. The 'sys' time represents
theSJAHER,MOOLAMATTOM
time taken by Unix to fire the command. Sigma Sathyan
38
Let's now time the same command by executing it with a higher nice value.
Note that this time the process consumes a significantly higher time to execute. However, the
time taken (user time) by the command to execute its own code has remained same.
Scheduling Of Processes
Linux can schedule processes to get executed within next few-seconds to next few years.
Once the user-has submitted a process to 'Linux directing it to execute the process at a
specified time and date in future, there onwards Linux takes over. Linux manages to
remember the processes to be executed and goes about executing them whenever the time
arises without needing any further directions from the user. That's the philosophy of
$ ps -e | grep cron
scheduling processes. Execute the following command:
147 ? 0:01 cron
Here the process cron stands for chronograph. This system process is responsible for
scheduling the other processes. Neither user nor super user can execute the executable file
(/etc/cron) of this process directly. During booting Linux executes this file and displays the
message 'cron started' on the host terminal. Once Linux launches this process there onwards
cron is activated once every minute. When cron wakes up it checks whether any scheduled job
is available for it to execute. If it is, it executes the job and goes back to sleep again, only to
wake up the next minute to once again carry out the check. This cycle goes on till the Linux
The isn't
system at command
shut down on the host machine. There are three commands which make use of the
cron command
This daemon's scheduling
is capable capability.
of executingThese
Unixarecommands
at, batch and
at a crontab.
future date and time. The Unix
commands can be specified at the command prompt or can be stored in a file and the at
command can use this file to execute the commands.
$ tty
/dev/tty3c
$date
Fri Jun 14 10:57:23 IST 1996
$ at 17:00
clear > /dev/tty3c
echo "It's 5 PM ! Backup your files and logout" > /dev/tty3c
Ctrld
Job 803108760.a at Fri Jun 14 17:00:00 IST 1996
SJAHER,MOOLAMATTOM Sigma Sathyan
39
On pressing Ctrl d the at command displayed the job-id and the date and time we requested
the two commands clear and echo to be executed. The job-id always terminates with a '.a'
indicating that this job was submitted using the at command. Once submitted this way, the
message would be echoed on our terminal at 5.00 PM sharp. It is necessary to redirect the
output of dear and echo to our 'tty' file. Otherwise the output of these commands would arrive
$ at 17:00
as mail from the cron daemon. Let us see:
echo "It's 5 PM! Backup your files and logout"
Ctrld
Job 853158864.a at Wed Jun 14 17:00:00 IST 1996
At 5 PM in the evening you would see a message on your screen saying 'you have mail'. To
examine what have you received in mail just type
$ mail
There are two options available with the at command which permit us to view the list of jobs
submitted using at and to remove any unwanted jobs from this job queue. These options are -1
for listing jobs and -r for removing jobs. While removing a submitted job its job-id should be
mentioned.
$ at –r 853158864.a
would remove the job '853158864.a' from the job queue.
While specifying the time at command permits a lot of flexibility. Following are some of the
specifications that can be used with at:
$ at 0915 am Mar 24
$ at 9:15 am Mar 24
$ at now + 10 minutes
$ at 7now
pm+Thursday
1 day next week
Instead of specifying the commands at the prompt, here we would make at read them from a
file and then execute them. Let's first create this file.
$cat > cmdfile
clear
echo "Hi there! Do you never get bored with working?"
Ctrld
Now we can ask the at command to read the commands from cmdfile as shown below.
$ the
Now at 5at
PM < cmdfile
command willJob
read853158870.a at Fri
the commands fromJuncmdfile
14 17:00:00 IST 1996
and execute them at 5 PM. Since
we have not redirected the output to our terminal it would be mailed to us by cron. System
SJAHER,MOOLAMATTOM Sigma Sathyan
40
administrator keeps tracks of two files at.allow, at.deny. Only those users whose login name
appears in these files are permitted to use the at command. He can edit these two files i.e., to
include
atq :or delete login names.
list the users pending jobs unless the user is the super user; in that case
everybody‘s job are listed. The format of output lines (one for each job) is jobno,date,
hour,jobclas.
atrm : delete jobs, identified by their job number.
However, this time cmdfile should not only contain commands which we wish to get executed
but also the details of date and time in a specific format. This format is shown below:
Minute Hour Day of Month Month of year Day of week Command
$ Ctrl d
Let us understand the commands that we have given in our cmdfile. The first one would be
used to echo the message at 10:30 am on first day of every month. th The second message would
mail that
Note the contents
each fieldofinthe file confi.letter
cmdfile to the
is separated user
either byaa2 on 17
a space or aNovember of'Month
tab. For the every year.
of year'
and 'Day of week' fields we have used a' *'. A '*' means all possible values. Another thing to
note is that Sunday
is represented as 0 in the 'Day of week' field.
When we execute the crontab command using the cmdfile
$ crontab cmdfile
the contents of cmdfile are automatically transferred to the /user/spool/cron/crontabs
directory where they are stored in a file which has the same name as your login name. There
onwards the cron daemon will read this file and execute the commands present in it on a
regular basis. As with the at command we can view the commands that we have submitted by
using the -l option
$ crontab -l with the crontab command.
To remove the submitted job we can use $ crontab -r
Here we are not required to specify the job-id since using crontab we can submit only one
command file. If we want to schedule a few more jobs we need to edit the cmdfile in our
home directory and then resubmit it using
$ crontab cmdfile
Once again cmdfile‘s contents would be transferred to /usr/spool/cron/crontabs directory
and would be stored in a file with our login name. Obviously the earlier file with this name
would be overwritten. As with at, here also there are two files cron.allow and cron .deny
which decide which users are permitted and which are prevented from using the crontab
command.
Redirecting input/output
In all OS there is a standard input device and a standard output device. In Unix also standard
input device is keyboard and standard output device is monitor (display screen). The standard
error device is also the display screen.
$ cat
Linux is open software. It was first
designed by Linus Torvalds.
Ctrl d
Linux is open software. It was first
designed
First by cat
we typed Linus Torvalds.
and then hit the Enter key. We didn‘t provide any input file name. Then
what we typed was gathered as standard input, and cat passed it on to the standard output
(screen).
3) Any command that accepts standard input also accepts input redirection.
Here the file newfile became the standard input, and cat read its contents and displayed them
on the screen. The same thing can be achieved by saying,
$ cat newfile
hai, how are you??
Hope you are all fine.
Though both the commands produce the same output there is a difference between the two. In
nd
the 2 case newfile was not the standard input. The standard input remained the terminal, and
the internal programming of cat caused the newfile file to be opened in addition to the
4) Cat can read the standard input and a file input during the execution of the command. The
standard input.
standard method is to use a hyphen – instead of a file name to stand for the standard input.
Here is an
nd example that uses the file newfile as the 1st input and the standard input (screen) as
the 2 input.
$ cat newfile –
ABCD
Ctrl d
hai, how are you??
Hope you are all fine.
st
ABCD
Catkeyboard
concatenated the two by
input denoted inputs. Since the
the hyphen filename
– was printed.came 1 , it was printed first then the
The 1 part of redirection, <currentfile , indicates that input is to be taken from the file
nd
currentfile and the 2 part of redirection, > newfile establishes that output is to be routed to
The order in which the two-indirection operators are used doesn‘t matter.ie,
the file newfile.
$ cat > newfile < currentfile
also produce same result.
6) Another redirection operator used is the append operator >>. It is similar to > except if the
target file already exists, the new output is appended to its end.
$ who >> logfile
This command appends the current list of users who have logged in to the end of logfile.
Redirection is a very powerful tool and is frequently used to redirect the output of a process
running in the background.
SJAHER,MOOLAMATTOM Sigma Sathyan
44
There are a few more redirection operators, used mainly in writing shell scripts rather than at
command prompt. They are as follows:
Operator Action
> file make file the std output
< filemake file the std input
>> file make file the std output, appending to it if it already exists.
<< word take shell input up to the first line containing word or up to end of file
make file the output for file descriptor n
n > file
cmd1 | cmd2 redirect
make standard output
standard outputof to
cmd1 the standard
standard error input of cmd2
1>&2
Connecting processes with pipes
Redirection helps to commands to files. Piping facility lets us connect commands to other
commands and operations. To send the output of one command as input to another command,
the two commands must be joined using a pipe symbol (|)
It is possible to join commands using a pipe since many commands accept input from standard
input and send output to standard output. Such commands are known as Filters.
A filter is a program that takes input from the standard input file, processes it and sends the
output to the standard output file. Linux provides various filters like cat, grep, wc, tr cut etc to
enable you to for
Examples work effectively with data.
piping:
1) $ ls | wc -l
Here the output of ls becomes the input to wc which counts the number of lines it receives as
input and displays this count on the screen. Instead of displaying this count, if we want to
store the count value in a file, use the output redirection as shown below:
$ ls wc –l > countfile
This example shows that piping and redirection can go together.
2) $ who | sort
Here, instead of displaying the output of who on the screen it is piped to sort. sort sorts
whatever
$ who | itsort
receives as input (output of who, in this case) and displays the sorted output
> sortedlist
(sorted
3) $ according
who | sort to first character
-logfile in each line) on the screen. Once again, if we want we can
> newfile
redirect this from
The output sortedwho
output to a filethe
becomes by saying,
standard input to sort. Meanwhile, sort opens the file
logfile. The contents of this file are sorted together with the output of who (represented by the
hyphen), and thethesorted
4) Unix offers output is to
tee command redirected
achievetothis
thepurpose.
file newfile.
It reads the standard input and sends
it on to the standard output. It also redirects a copy of what it has read into the file (if any) of
your choice. For example:
SJAHER,MOOLAMATTOM Sigma Sathyan
45
$ who | tee logfile | sort
Here, the output of who becomes the standard input of tee. tee now sends one copy of the
input to sort through one pipeline, whereas the other copy is stored in a file called logfile.
If we want to store the output of who in two files and still manage to send one copy to sort.
$who the
Mention | teetwo
logfile newlogfile
filenames | sort
after the tee command as shown below:
5) We want to store the output of who in filel and file2, display the same output on the screen
and store the sorted output in file3. It can be done:
$ who | tee filel file2 /dev/tty3a | sort > file3
Here, in addition to filel and filel we have used the file associated with our terminal
(/dev/tty3a). Hence tee sends the output of who to all the three files. What is sent to
/dev/tty3a is promptly displayed on the screen. The copy which is sent to sort is first sorted
and the sorted output is then stored in the file file3.
6) If you wish to append the output of tee to a file, just use its -a option as shown below:
$ cat file1 file2 | tee -a completefile | more
In this pipeline the output of cat (contents of the files filel and file2) are appended to the
existing contents of the file completefile. Another copy of output of cat is sent to more for
displaying on the screen.
7) We can however also redirect the standard error. The following example shows this can be
done.
$ cat myfile > newfile 2> errorfile
If the file myfile exists, then the contents of that file would be copied into newfile. If it does
not exist, then an error message would be produced. Instead of displaying the error message
on the screen it would be redirected to a file errorfile. Note that the > symbol redirects the
Assuming
standard that whereas
output the file myfile did not the
2>redirects exist let's check
standard out the
error. contents
While of errorfile.
redirecting the standard
$ cat
output errorfile
instead of > we may as well use 1>.
cat: cannot open myfile
This is the error message produced by the cat command when it failed to locate the file
myfile. Obviously, had myfile existed its contents would have been copied into the file
newfile.
Printing commands
lp command – It is used to send the user‘s print job to the print queue. When we submit the
job for printing using lp command, it returns a request id. This id can be used to keep track of
our job or to cancel it if required. lp adds a banner page at the beginning of our print out so
that we could identify our print out from large number of users.
SJAHER,MOOLAMATTOM Sigma Sathyan
46
$ lp file1 file2
request id is lp –32(2 files)
Using –w option with lp we will informed if the print job is completed. If we logout before the
completion of print job we will be informed through mail.
$ lp –w file1 file2
request id is lp –44(2 files)
lpstat command - We can watch the status of our print job using lpstat command. The –t
option with lpstat gives status of all print jobs on the queue, type of printer, whether it is
accepting any fresh prints requests etc.
$ lpstat –t
To cancel a print job uses cancel command.
$ cancel lp –13
where lp –13 is the request id of our print job. The cancel command responds with:
request ―lp –13,190 canceled
Options used with lp:
-w sends a message to user when file is printed
-n num prints num number of copies. Default is 1
-o nobanner doesn‘t print the banner page
-P list prints the page numbers specified by list
-d printer specifies a printer other than default printer
The-qprint
levelschedulersets
called lpsched
apriority levelmanages the job.(
for the print printLowest
jobs submitted
is 39) to print queue. It is
usually executed at the time of booting. If not system admin can run this by saying: #
/usr/lib/lpsched
The system admin can terminate print services by using the command: # /usr/lib/lpshut
lpr command - We can also use lpr command in Linux to get a hard copy of the document.
$ lpr projectrep.doc
The lpr command makes a copy of our file and pushes it in the system‘s print queue. This
process is called spooling, so we can change or delete the original file without harming your
printout.
Options used with lpr:
-r tells the system to delete the file after printing.
-s tells the system top print directly from the original file instead of spooling to the print
queue. With this –s option we can‘t modify or delete the original file while it is printing. It is
useful in saving a bit of time since no copy is made when the original file is big.
$ lpr –r report delete the file report after printing.
pr commnad- Convert text files for printing. Paginate or columnate FILE(s) for printing.
It displays the contents of the specified file adding with suitable headers and footers. It can be
used with lpr command for neat hard copies. The header part consists of last modification date
and time along with filename and page number.
Syntax:
pr [option]... [file]...
1 1005
2 1002
3 1003
4 1001
----Note that remaining lines are empty--------
5 1004
$ pr -3 e1
Example:
$ Find /home/Steve -name "jan"
/home/Steve/2000/jan
/home/Steve/2001/jan
Here /home/Steve is the name of the directory in which specific files need to be located. The –
name ―jan‖ option specifies that all the files with the name jan are to be located. Consider the
file hierarchy of the /home directory.
When you use the command with out –name option, the command displays the path names of
all files in the specified directory and its subdirectories. It is shown below:
$ find /home/Steve
/home/Steve/2000
/home/Steve/2000/df
/home/Steve/2000/jan
/home/Steve/2000/feb
/home/Steve/2000/temp
/home/Steve/2001
/home/Steve/2001/df
/home/Steve/2001/jan
/home/Steve/2001/temp
/home/ Steve/ Desktop
/homeSteve/progs
/home/Steve/progs/a. out.
/home/Steve/progs/report
The option f with -type searches for all the ordinary files. To search for directory files, you
need to type the following command:
$ find /home/Steve -type d
Example:
$ find . -name temp -type f -ok rm {} \;
To locate the file dmesg, you need to type the following command:
$ find / -name dmesg
To view the contents of the contents of the file, you need to type the following command
$ find / -name dmesg -exec cat {} \;
wc command
It counts the number of lines word and characters in the specified file or files. It comes with
options –l, -w, -c that allows the user to get the number of lines, word, and characters
individually or in any desired combination.
$ wc –lc file1 file2
file1 20 571
file2 30 804
SJAHER,MOOLAMATTOM Sigma Sathyan
51
Thus the file1 contains 20 lines, 571 characters. File2 contains 30 lines and 804 characters.
The wc command is capable of accepting input directly from the keyboard. By entering wc
without arguments, it waits for the user to type in the input. On terminating input (using ctrl
d), [mca@chavara
the appropriate ~]$
counts
wc are displayed for the input that you supplied.
bca bba bcom
mca mba mcom
3 s3 9
s1 s2 35
sort command
It can be used for sorting the contents of a file. It can merge multiple sorted files and store the
result in the specified output file. Sorting is done according to the ASCII collating sequence.
$ sort myfile
This would the sort the contents of myfile and display the sorted contents on the screen.
$ sort – file1
Sometimes we may want to combine the contents of a file with the input from the keyboard
and then carry out the sorting, using the above syntax. Here - stands for standard input
keyboard.
$ sort
We can even sort only the input from standard input by the above format. Since no file has
been specified here it is assumed that the input is to come from the standard input device.
Sort is used most fruitfully for files which are essentially databases, or which its information
arranged in fields. We can specify the fields for sorting. Such fields are known as sort keys.
The syntax of the sort command includes optional +posl and -pos2, signifying the starting and
ending position of the sort key. If -pos2 is not included, then the key is assumed to extend till
the end of
Assume thea line.
that file students has four fields, for roll number, names of the students, their marks,
Examples:
1) $ cut –f 2,7 empinfo
A database table empinfo contains many fields. The above cut command selects/displays
2nd.7 field and its details.
th
paste4command
This command concatenates the contents of the specified files into a single file vertically.
(Like cut command separates the columns, this paste command merges the columns.)
Syntax
$ paste <filename1><filename2>
[mca@chavara ~]$ cat >e1
1005
1002
SJAHER,MOOLAMATTOM Sigma Sathyan
54
1003
1001
1004
$ cat >e2
computer
zoology
commerce
computer
botany
$ paste e1 e2
1005 computer
1002 zoology
1003 commerce
1001
1004 botany
computer
join command
This command is used to join lines of two files on a common field. It displays a line for a pair
of input lines in which one line is from file1 and other from file2. Both of them have same
value in the join field.file1 and file2 should be already sorted in increasing order of their join
fields.
$ cat file1
1 ANU
2 BINU
3 PAUL
4$ catANN
file2
2 FIRST
4 SECOND
7 CAMEL
$ join file1 file2 > file3
2 BINU FIRST
4 ANN SECOND
who
Since Linux is a multiuser system ‗who‘ will display the users are currently logged on.
[mca@chavara ~]$ who
mca tty1 Dec 19 13:57
Mathematical commands
factor
Print the prime factors of each NUMBER. Print the prime factors of all specified integer
NUMBERs. If no arguments are specified on the command line, they are read from standard
input.
[mca@chavara ~]$ factor 2
2: 2
[mca@chavara ~]$ factor 12
12: 2 2 3
[mca@chavara ~]$ factor 13
13: 13
[mca@chavara ~]$ factor
15: 3 5
a
expr
factor: `a' is not a valid positive integer
It
+ is used to perform arithmetic operations on integers.
Addition
[mca@chavara ~]$ factor
15 -* Subtraction
Multiplication
/ Division (decimal portion will be truncated,division is done only on integers, gives the
quotient only)
% Remainder of division (modulus operator)
A white space must be used on either side of an operator. The * operator has to be escaped to
prevent the shell from interpreting it as the filename metacharcter. So use \ before the *
character.
SJAHER,MOOLAMATTOM Sigma Sathyan
56
[mca@chavara ~]$ x=5
5 result in decimal
$ bc
obase = 2 set obase to binary
5 type the input in decimal number
101 result in binary.
$ bc
ibase = 16 set ibase to hexadecimal
B type the input in hexadecimal number
11
$ bc result in decimal
obase = 16 set obase to hexadecimal
11 type the input in hexadecimal number
B result in hexadecimal
bc also supports functions like sqrt,sine,cos tec.
$ bc
sqrt(169)
13
To find sine, cosine etc use bc –l
$ bc -l
s(0)
0
c(0)
1.00000000000000000000
$ bc –l
s(3.14)
Creating and editing files with vi editor.
.00159265291648695254
Text Editors
scale = 2 A text editor is a program that enables you to create and modify text files.
Typically,
s(3.14) a text editor provides a screen with a fixed line length and line numbers. You can
type
0 text line by line, navigate through the documents by using different commands, and save
the document.
A text editor is usually less preferred by users over a word processor because a word
processor offers additional features, such as text formatting. You can use a text editor to:
Create andprograms
Create edit documents.
and utilities.
Write e-mail messages.
You can use the restricted editor or red to edit files in the current directory. You cannot
execute shell commands by using the red editor.
The joe Editor
Another popular editor available is the Joe's own editor or joe. You can invoke the joe editor
by typing joe at the command prompt. You can also give a file name along with the joe
command to open the file in the editor. The joe editor is a fu'1-screen editor that lets you edit
both programs and text.
The pico Editor
The pico editor is based on the Pine messaging system. The Pine messaging system is a
character-based interface in Linux. You can use the Pine messaging system to send and
receive e-mail messages. The pico editor offers various features, including paragraph
justification and search features. In addition, the pico editor provides a spelling checker and a
file browser. In the pico editor, commands are displayed at the bottom of the screen. The pico
editor also offers context-sensitive help. Among the above editors; vi and emacs are the most
Vi editor
widely used.
It is ascren oriented text editor developed by Bill Joy in 1976.Commands are entered through
keyboard. We can also use mouse support and a GUI version with scrollbars and menus can
be activated.
Disadvantages of vi editor
1) The user is always kept guessing. There are no self explanatory error messages.
2) There are no online help available in vi editor.
3) In each 3 modes of operation, each key pressed has different meanings. So each key press
effect has to be minimized.
4)5) ViItishandles
case sensitive.
files thatA‟h‟ moves
contain text. the
Youcursor one position
can create to files
files, edit the left.
andAprint
„H‟them.
positions it at
the
6)top
It left
can‘tcorner.
do boldface, running headers or footers, italics.
Modes of operation
1) Command mode: To switch to command mode Press ESC key. Here all keys pressed
by the user are interpreted as commands. The keys that are hit are not displayed on the screen.
2)
Insert mode:
replacements of text.It In
is activated by the
insert mode pressing „i‟. Itwe
characters allows insertion
type are addedoftonew text,Itediting
the file. is alsoand
known as input text mode.
3) The ex command mode: It permits us to give commands at the command line. The
bottom line of the vi screen is called the command line.vi uses command line to display
messages and commands. All commands entered in this mode are displayed in the command
line. It is so called because commands given in this mode are compatible with the commands
ofSJAHER,MOOLAMATTOM
the ex editor. Sigma Sathyan
60
Running vi
To run vi and create a new file, simply run the command 'vi' from any shell prompt:
$ vi
Alternatively, to load an existing text file into vi, run the command 'vi [filename]', from the
shell prompt: $ vi myfile.txt
Your file will be loaded into vi, and the cursor will be placed at the beginning of the first line.
Note that an empty line is shown as a tilde (~).
Probably the most basic and most commonly used commands are those used to move the
cursor around the screen. The cursor is the 'pointer' to the current position in the text, and is
usually represented as a flashing underscore character.
To move the cursor around the screen, you must be in command mode. On some systems, you
may use the standard 'cursor keys' on your keyboard to move the cursor. However, on many
systems, this will not work. This mainly due to historical reasons, dating back to when not all
terminals had cursor keys. If cursor keys do not work on your system, then use the following
keys instead:
h - Cursor left
j - Cursor down
k - Cursor up
l - Cursor right
Deleting a character
While you are in insert mode, you can delete a character that you have just typed by using the
'backspace' key - this is similar to most other editors and word processors. But there is a
difference: You may only delete characters that you have entered in this session of insert
mode.
Repeating a command
To repeat a command, simply type the number of times to run the command before the
command itself. For example, to delete 20 characters from a file, starting from the current
position, using the command '20x'. Note that the command does not appear at the bottom of
the screen, so you have to keep track of what you're typing yourself.
Deleting a line
Just one more command to learn for now. We've seen how to delete a single character with the
'x' command. There is a quicker way to delete an entire line: with the 'dd' command.
vi command summary
The following tables contain all the basic vi commands.
Starting vi
Command Description
Command Description
:e file edit file (save current file with :w first)
quit vi
:q
:wq save the file and quit vi
} start of paragraph
1G
end of paragraph
nG line n
top of file
G end of file
<Ctrl>W first character of insertion
<Ctrl>U up ½ screen
down ½ screen
<Ctrl>D
up one screen
<Ctrl>B
down one screen
<Ctrl>F
Inserting text
cw word
cc current line
five lines
5cc
current character only
rR
current character and those to its right
s
current character
S current line
~ switch between lowercase and uppercase
Deleting text
d{ to beginning of paragraph
d} to end of paragraph
:1,. d
to beginning of file
:.,$ d
to end file
whole of file
:1,$ d
Using markers and buffers
Command Description
mf set marker named ``f''
`f go to marker ``f''
´f go to start of line containing marker ``f''
"s12yy copy 12 lines into buffer ``s''
"ty} copy text from cursor to end of paragraph into buffer ``t''
"ly1G copy text from cursor to top of file into buffer ``l''
"kd`f cut text from cursor up to marker ``f'' into buffer ``k''
"kp paste buffer ``k'' into text
Searching for text
Search Finds
/and next occurrence of ``and'', for example, ``and'', ``stand'', ``grand''
?and previous occurrence of ``and''
/^The next line that starts with ``The'', for example, ``The'', ``Then'', ``There''
/^The\> next line that starts with the word ``The''
/end$ next line that ends with ``end''
Command Description
:s/pear/peach/g replace all occurrences of ``pear'' with ``peach'' on current line
Expression Matches
. any single character
zero or more of the previous expression
Miscellaneous Commands
Type: To:
Option Effect
all list settings of all options
ignorecase ignore case in searches
list display <Tab> and end-of-line characters
mesg display messages sent to your terminal
nowrapscan prevent searches from wrapping round the end or beginning of a file
number display line numbers
SJAHER,MOOLAMATTOM Sigma Sathyan
66
Block commands
As their name suggests these commands work on a group of lines (a block of text) rather than
an isolated line. For example we may want to delete a group a group of lines from the file by
using a single command. Or we may want to copy a group of lines from one part of the file to
another. We can make block commands to work on single lines. To be able to use block
commands we must remember two things:
(a) All the block commands work in ex command mode
(b) Line numbers should be associated with the text before we issue any block commands.
This is so because block commands need to be told the line numbers on which they are
supposed to operate.
For example, a block command like :4,12d indicates that lines 4 to 12 should be deleted from
the file currently loaded in vi.
While issuing this command if the line numbers are displayed on the screen, we can promptly
issue block commands. To display line number: you have to give a command (Esc) :set
number or (Esc) :set nu in the ex command mode. Once line numbers are displayed we can
issue block commands:
:2,4d deletes line numbers 2 to 4
When you don‘t want to use block commands and no longer want line numbers to be
displayed use
Command function
In most common editors like wordstar we can use shorthand characters for commonly
required expressions. These shorthand commands can be invoked at the press of a single key
for users convenience.
In vi we can use abbr for this purpose; which stands for abbreviation. We often use printf in
C program.We can abbreviate printf as pr for convenience. For this we have to do:
Now when you type the program and you press „p‟ followed by „r‟ they appear on the screen
as they are. But if you follow them with a space or the Enter key the instantly overwritten by
the word „printf‟.
To see the entire list of macros that you have set you use the command: (Esc) :abbr
When not required you can unabbreviated it as follows (Esc) : una pr
Command Function
$ vi + 100 file Loads file and places the cursor on the 100th line in the file.
$ vi +/pattern file Loads file and places cursor on the first occurrence of matching pattern.
Displays file in read only mode of vi. Any changes made to the buffer
$ view file
will not be allowed to be written to the file.
ABSOLUTE PATHS
An Absolute Path is easily recognized from the leading forward slash, /. A Slash (/) means
that we start
at the top level directory and continue down.
For example to get to /home/users, we will type:
$This is an absolute path because we start at the top of the hierarchy and go downwards from
cd /home/users
there.
RELATIVE PATHS
A Relative Path do not have a preceding slash. We use a relative path when start from a
directory below
the top level directory structure. This is dependent on where we are in the file system.
For example if you are in root's home directory and want to get to /root/kerala, you type:
$ cd kerala
We can also use absolute addressing as -
# ls /usr/bin
This command lists the files in /usr/bin directory using absolute addressing.
SJAHER,MOOLAMATTOM Sigma Sathyan
TO DISPLAY only file size $ du –s –h filename
69
UNIT 3 SYSTEM ADMINISTRATION
The prime role is user administration (set up and maintain user accounts)
To implement security policies for use of the computer system and network.
To formulate security policies for users. A system administrator must have a strong grasp of
computer security. (Firewalls and intrusion detection systems)
The system administrator can carry out these jobs in 3 ways:
Writing small shell scripts which in turn use the tools (system admin tools).
Common Administrative Tasks
The Common Administrative Tasks can be classified as:
System automation which includes: the free disk space checking and reporting periodic
backups, data for the system performance, user account maintenance (creation, deletion etc),
Business specific functions (pushing data to a web server, running monthly/quarterly/yearly
report, etc.)
Documentation: A good system administrator should document Policies, Procedures, and
Changes.
Communication: A good system administrator should be a good communicator too. All the
users should be aware of at least three points about a system administrator: what he is going to
do, what he is doing, what he has done.
Identifying Administrative Files Configuration and Log files
Linux files are grouped according to their functionality and usage, so there are separate
directories for configuration and log files.
Configuration files: The directory for such file is the /etc directory. Most of the configuration
files resides in the /etc directory. Some of them are as follows:
/etc/passwd contains user password and login configurations
Options Meaning
-c comment provide a description of new user account. Usually the person‘s full
expires.
SJAHER,MOOLAMATTOM Sigma Sathyan
71
Examples
$ useradd –c ―MarySmith‖ mary
To create we have to login as root user. Here a new user MarySmith with login name mary is
created.
$ passwd mary
Changing password for user mary
New password:******
Retype new password : ******
$ useradd –m –g users –G wheel, sales –s /bin/tcsh –c ―MarySmith‖ mary
The useradd command is told to create a home directory for mary (-m), make users the
primary group she belongs to (-g), add her to the groups wheel and sales and assign tcsh as her
primary command shell (-s).
Modifying users with usermod command
Use the usermod command to modify user accounts. You must provide account details to
change followed by login name of the account.
Options used with usermod
Options Meaning
-c comment change the description field of the account
-d home_dir change the home directory of the account, with-m option copy the contents
of home directory. Replace home_dir with full path to new directory.
-e expir_date Assign a new expiration data replacing expire data with date in mm\dd\yy.
-f inactivity Set the number of days after a password expires until the account is Permanently
disabled.
-g group Change the primary group that the user is in replace group with name of
new group.
-G g Set the list of groups that user belongs to. Replace group list with a list
of groups.
-l login_name change login name of account to the name supplied after –l option.
-m This option is used only in conjunction with –d option. It causes the contents
groupadd command
With groupadd command you can create new groups. When you add a group to the system,
the system places the group‘s name in the /etc/group file and gives it a group ID number. This
command creates the group category. Users are individually added to the group.
Examples
To create a group called engine. $ groupadd engines
groupdel command
You can delete a group with the groupdel command. To delete a group engines use the syntax:
$ groupdel engines
groupmod command
You can change the name of a group or its ID using the groupmod command. Enter
groupmod –g with the new ID number and the group name. To change the name of a group
use the –n option. Enter groupmod –n with the new name of the group, followed by current
name.
$ groupmod -n trains engine.
Here the engine group is changed to new group name trains.
The following example creates a directory called ‗engines‘ and changes its group to that of the
‗engines‘ group.
$ mkdir /home/engines
$ chgrp engines /home/engines
Then the read, write execute permissions for the group level should be set:
$ cp mymodel /home/engines
It copies the mymodel file to the /home/engines directory
It sets the group read and write permissions to the engines group.
Note:
Red Fat user Manager provides you a Graphical User Interface (GUI) to add, modify view
delete users and groups from Linux OS. To open the Red Hat Manager you need to type the
command at the shell prompt:
$ redhat-config-users
You can also invoke the Red Hat User Manager from the GNOME desktop by selecting
Mount Point refers to the empty directory in the currently available file system with
which a newly created or additional file system is mounted. It then becomes the root directory
of the added directory tree. This tree is accessible from the directory to which it is mounted
known/mnt
The as the mount point.
directory already exists in Linux by default on all Unix like systems. This
directory with its subdirectories like /mnt/floppy , /mnt/usb are intended specifically to be
used as mount points for removable media such as CDROMS, USB key drives and floppy
disks.
Mounting can be done by the root user by using the mount command with the name of
the device to be mounted and its mounting point / destination.
For eg: to mount the second partition on the first HDD , which is designated by /dev/hda2
, using a directory named / BCA as the mount point we use - $ mount /dev/hda2/BCA
We can remove the connection between the mounted device and the rest of the file
system. This process is called Unmounting. It is done by executing the umount command,
followed by the name of the device to be detached or unlinked and its mount point. For eg : to
umount the second partition from the root file system We use the command:
$ umount /dev/hda2/BCA
An updated list of the devices that are mounted on the Linux can be seen at the /etc/fstab
file. This text file also displays the mount points and other information about the devices. It
can be viewed by using the command
$ cat /etc/fstab
Note
Use the command ls –i to check the inode number of a file.
$ ls – i Myfile
Output : 534634 Myfile
We can also use stat command to find out inode number and its attributes. $ stat Myfile
Output:
File: Myfile
Size : 1988 Blocks : 8 IO Block : 4096 regular file
Device: 341/833d Inode :32820 Links : 1
Access : (0644/-rw-r—r--) UID : ( 0/ root) GID : ( 0/ root)
Access : 2009-11-10 01:16:01.00000000 +0530
by Linux
The mkfs command initializes a file system on a new partition
Warning: any old data on the partition will be lost
For example, to make an ext2 filesystem on /dev/hda2: # mkfs -t ext2 -c /dev/hda2
-t sets the file system type to make, and -c checks for bad blocks on the disk
Working
mkfs useswith
otherpartitions
programsin
to Linux
make specific types of file system, such as mke2fs and mkdosfs
The fdisk command with the option –l qualifier display the current partition tables along with
the Hard Drives to the workstation/server as :
$ fdisk –l
Once we have determined which hard drive to partition, we can run the fdisk command
followed by the hard drive. Here we will use the first hard drive (sda).
$ fdisk /dev/sda
Once fdisk command is executed, our command prompt will change to ―Command (m for
help):‖ and we will be ready to examine and partition the hard drive. The commands which
are supported by fdisk can be displayed by pressing the ―m‖ character followed by the Enter
key. The commands which will be used are ―p‖ for printing the partition table, ―n‖ for
creating a newthe
Displaying partition
currentandpartition
―w‖ fortable
saving the changes and exiting.
The first step before partitioning the hard drive is to get the disk space availability and what
the current partition table looks like. The character used with the fdisk is the ―p‖ which print
current partition table.
Creating a new partition
The next phase is to create the new partition. For example, we will create a partition of type
―Linux‖ with the partition size of 1 GB. The command to create a new partition is the ―n
character, we will enter what cylinder to star from (User should select the Default) and the
size of the partition.
Writing the new partitions to disk
Now we have the newly created partition and we save the changes by issuing the ―w‖
character which write the new partition table to hard disk as
Activating the new partition
After the new partition table ahs been written to the hard disk, Kernel can read the new
partition without rebooting. The first step is to create a mount point for the new partition. Here
we will use ―/media/newpartition‖ and the command ―partprobe‖ to have the kernel read the
partition table –
LINUX:~ # mkdir/media/newpartition
LINUX:~ # partprobe
Now we can format the partition and place a file system of our choice on it, (EXT2, EXT3,
REISERFS). Suppose we have chosen the RESIERFS file system –
LINUX:~ # mkfs.reiserfs /dev/sda6
Once we have the partition properly formatted with the file system, now we can mount and
use the newly created partition as LINUX:~ # mount /dev/sda6/media/newpartition
LOGIN TO LINUX
Linux never allows anybody to enter without user name and password. For example:
login:arjun
password:
Linux doesn‘t show your password, not even Asterisks (*) when we type it. It is for safety.
Old password:
New password
Retype new password:
SJAHER,MOOLAMATTOM Sigma Sathyan
79
$
If the two passwords we type don‘t match, the password remains unchanged. This is due to
safety precaution – if we made a mistake typing the new password and Linux only asked you
once , then our password may be changed to some new value and we will have no way of
knowing that password.
$ passwd arjun this command will change arjun‘s password
Examples :
a) To display the host name
[mca@chavara amitha]$ hostname
chavara.santhigiri.net
b) Display the IP address of the system
-s, --kernel-name
-n, --nodename
print the network node hostname(it is the name by which system is known to the
network)
-r, --kernel-release
-v, --kernel-version
[mca@chavara amitha]$ uname
Linux
[mca@chavara amitha]$ uname -p
i686
[mca@chavara amitha]$ uname -a
Linux chavara.santhigiri.net 2.6.9-42.0.0.0.1.ELsmp #1 SMP Sun Oct 15 14:02:40 PDT 2006
i686 i686 i386 GNU/Linux
-I Install package
-e Remove package
-qi Display information for an installed package
-qpl Display file list from an RPM package file.(Used for an uninstalled package)
Examples:
$ rpm –Uvh mozilla -1.orc3 -0.1386.rpm
$ rpm
The –eremoves
user xtetris the xetris game from the system.
$ rpm –qi xv
Display information about the installed package.
$ rpm –ql xv
Display a listing of files a given RPM package contains.
This command uses anonymous FTP i.e., no username and password required. The URL
may also contain a username and password preceding the hostname.
$ rpm –i ftp://username:password@ftp.mguniversitynotes.com/Antivirus.rpm
#
When we try to install the rpm package check the database for dependencies. If RPM do not
find those dependent files in the database, the installation will stop & display warnings of
Failed Dependencies.
When RPM shows a dependency error it displays a list of files that are required. We can
bypass the dependencies and install the software without installing those dependent programs.
We should use the --nodeps option to tell RPM not to check any dependencies before
installing the package.
# rpm –i MYSOFTWARE.rpm --nodeps
This command forces rpm utility to ignore dependency errors and install software anyway.
One point should be noted that if the needed files are missing anyway, the software will not
work well or not at all.
Password is stored in /etc/shadow file
The encrypted password of any user is not stored in /etc/passwd file. It is stored in the
/etc/shadow file. It is another method of storing user account information with the shadowpassword
format.
SJAHER,MOOLAMATTOM Sigma Sathyan
83
The ―/etc/shadow‖ file contains password as well as other information such as account or
password expiration values etc. It is readable only by the root account and is therefore less of
a security risk. Almost all Linux OS use shadow password suite, where /etc/passwd has
asterisks (*) instead of encrypted password.
The /etc/shadow file contains password and account expiration information for users. As with
passwd file, each filed in the shadow file is also separated with ― : ― . It contains fields like
username (up to 8 characters) password (13 characters encrypted), no: of days indicating
password last changed etc.
#! usr/bin/tail +2
This account has been closed due to security breach.
Please call 555 – 1234 and wait for the men in black to arrive.
The first two characters (#!) tell the kernel that the rest of the line is a command that needs to
be run to interpret this file. The tail command in this case outputs everything except the first
line to the standard output.
Example: If user Anuj is suspected of a security breach, the system administrator would do
something like this:
# chsh –s
/usr/local/lib/no-login/security anuj
# su – tester
This account has been closed due to a security breach.
Please call 555 – 1234 and wait for the men in black to arrive.
#
The purpose of su command is to test that the change worked. Tail scripts should be kept in a
separate directory, so that their names do not interfere with the normal user commands.
(2) To disable a user account, edit as root the ― /etc/shadow‖ file (assuming you are using
shadow passwords) if not edit the ― /etc/passwd ― file instead and replace the password (
which is stored in its encrypted form ) with a * character. All Unix passwords, regardless of
length (up to a minimum of 8 characters), are stored in the password file as encrypted strings
of 13 characters. Therefore by replacing the password with a single * character it is
impossible for the user to login. This method will require you to assign a new password to the
user if you re enable the account, since the encrypted password field will have been replaced.
One solution to this which seems to be popular among system administrators is to simplify
File Access Permissions FAP
prefix the * character in front of the encrypted password to disable the account, and simplify
FAP helpsthe
removing to*secure files
to enable it. and folders. File access permissions refer to the permissions
associated with a file or directory with the respect of the following:
File Owner
Group Owner
The
Other Users
Permissions that can be granted or revoked are symbolically represented by the letters
r,w,x .
The Permissions for a file or a directory are:
chmod <mode><filename>
We can use 2 modes with the chmod command
1) Symbolic mode- The Permission and the user type are specified as symbols
2) Absolute Mode-The Permission is specified as numbers.
Absolute Mode- In this mode we are using a series of digits to represent the file access
permissions. The Following table explains the number that denotes each type of permissions:
Number Permission
4 Read
2 Write
Execute
1
To get the permission bits you want, by add up the numbers accordingly. For example, the
rwx permissions would be 4+2+1=7, rx would be 4+1=5, and rw would be 4+2=6. We are
assigning separate permissions for the owner, group, and others, so we need a three-digit
Example:
number representing the permissions of all these groups.
$ chmod 755 testfile
This would change the testfile's permissions to -rwxr-xr-x. The owner would have full read,
write, and execute permissions (7=4+2+1), the group would have read and execute
permissions (5=4+1), and the other users would have the read and execute permissions as
SJAHER,MOOLAMATTOM Sigma Sathyan
86
well.
$ chmod 640 testfile
In this case, testfile's permissions would be -rw-r-----. The owner would have read and write
permissions (6=4+2), the group would have read permissions only (4), and the others
access permissions (0).
wouldn't have any
Symbolic Mode
In symbolic mode we are using symbols to specify the permissions and the types of the users.
The Following table represents the symbolic notation for the users.
The symbolic mode uses an operator to specify how the modes of a file should be
adjusted. The
following operators are accepted:
+ granting a permission to a class of users
Example:
Assigning Execute Permission to the Owner
chmod u+x file1
chmod u-x-w file1 Revoking Execute abd write Permission from the Owner
We can change the owner and group ownership of files and directories with the chown and
chgrp commands.
< CHOWN - CHANGE THE OWNER OF A FILE >
You can change the owner and group of a file or a directory with the chown command. You
can do this only if you are the root user or the owner of the file. Set the file's owner:
$ chown username somefile
After giving this command, the new owner of a file called somefile will be the user username.
The file's group owner will not change. Instead of a user name, you can also give the user's
numeric
You canID here
also set ifthe
you want.
file's group at the same time. If the user name is followed by a colon and
a group name, the file's group will be changed as well.
$ chown username:usergroup somefile
After giving this command, somefile's new owner would be user username and the group
usergroup.
You can set the owner of a directory exactly the same way you set the owner of a file:
$ chown username somedir
Note that after giving this command, only the owner of the directory will change. The owner
of the files inside of the directory won't change.
In order to set the ownership of a directory and all the files in that directory, you'll need the -R
option:
$ chown -R username somedir
Here, R stands for recursive because this command will recursively change the ownership of
directories and their contents. After issuing this example command, the user username will be
the$owner
chownof-vthe directorysomefile
username somedir, as well as every file in that directory. Tell what happens:
changed ownership of 'somefile' to username. Here, v stands for verbose. If you use the -v
option, chown will list what it did (or didn't do) to the file.
The verbose mode is especially useful if you change the ownership of several files at once.
For example, this could happen when you do it recursively:
In addition to chown, you can also use the chgrp command to change the group of a file or a
directory. You must, again, be either the root user or the owner of the file in order to change
the group ownership.
chgrp works pretty much the same way as chown does, except it changes the file's user group
instead of the owner, of course.
$ chgrp usergroup somefile
After issuing this command, the file somefile will be owned by a user group usergroup.
Although the file's group has changed to usergroup, the file's owner will still be the same.
The options of using chgrp are the same as using chown. So, for example, the -R and -v
options will work with it just like they worked with chown:
echo command
Use echo to display text or value of variables.
Options used with echo:
-n do not output the trailing line
-e enable interpretation of the following backslash escaped characters in the strings:
\a alert (bell)
\b backspace
\c suppress trailing new line
\n
\t new line
\r
\\ carriage return
Shell Keywords
horizontal tab
Keywords backslash
are the words whose meaning has already been explained to the shell. The
keywords cannot be used as variable names because if we do so we are trying to assign anew
meaning to the keyword, which is not allowed by the shell. The keywords are called Reserved
words. Given below are list keywords used in Bourne Shell:
echo, read, set, unset, readonly, shift, export, if, else, fi, while, do, done, for, until, case, esac,
break, continue, exit, return, trap, wait, eval, exec, ulimit, umask
Shell Variables
They are an integral part of shell programming. It provides the ability to store and manipulate
information within a shell program. The variables you use are completely under your control.
We can create and destroy any number of variables as needed to solve the problem at hand.
The rules for building shell variables are as follows:
SJAHER,MOOLAMATTOM Sigma Sathyan
91
A variable name is any combination of alphabets, digits and an underscore.
Variable name are case sensitive. I.e., Name, NAME, name, Name are all different variables.
Eg: si_int
m_hra
pop_e_89
MAILCHECK Defines the duration after which the shell checks whether the user has
received any mail. By default its value is 600 seconds.
IFS Defines the Internal Field Separator, which is a space, a tab, or a new line.
SHELL Defines the name of your default working shell.
TERM Defines the name of the terminal on which you are working.
HOME=/usr/veena
HZ=100
IFS
LOGNAME=veena
MAIL=/usr/spool/mail/veena
MAILCHECK=600
OPTIND=1
PATH=/bin:/usr/bin:/usr/veena:/bin:.
PS1=$
PS2=>
SHELL=/bin/sh
TERM=vt100
TZ=IST-5:30
$ x=${today}th
Now, x would contain the value 20 th.
However the following command will not produce the desired result because the shell will
look for a variable named todayth:
$ x=$todayth
The braces are optional in case you are not concatenating variables. The following two
commands will have the same result:
$ x=$today
$ x=$ {today}
$ Variable
a=20 a is declared and assigned a value of 20. To display the value of variable use ‗echo‘
$ echo $a or $ echo ${a}
20
If we avoid $ simply the variable a will be displayed.
$ echo a
a$ b=12
$ echo $b
12
$ echo ― $b ‖
12
$ echo ‗ $b ‘
$b
Note:
$ echo ` $b `
All12
shell variables are string variables. In the statement a=20, the ‗20‘ stored in a is treated not
as number, but as a string of characters 2 and 0. We can not carry out arithmetic operations on
them unless we use a command called expr.
A variable may contain more than one word. In such cases the assignment must be made using
double quotes.
$ c=‖two words‖
$two
echo $c
words
$ name=johny age=10
$ echo $name $age
$ johny 10
We can also use:
$ echo Name of the boy is $name, and his age is $age.
Name of the boy is johny, and his age is 10.
All variables defined inside a shell script die at the moment the execution of the script is over.
A variable which has been defined but has not been given any value is known as null variable.
A null variable can be created in any of the following ways:
$ d=‖‖
$ d=‘‘
$ d=
On echoing a null variable , only a blank line appears on the screen.
$ a=‖‖
$ echo $a
$
If a null variable is used anywhere in a command the shell manages to ignore it. For example:
$ var1=‖‖
$ var2=‖‖
$ wc –l $var1 $var2 file1
Since the var1, var2 were null variables the shell promptly eliminated them from the
command line and displayed the number of lines present in the file1.
Not only the system variables but also the user defined variables defined at the $ prompt or in
a shell script can be displayed using set command.
Reading a value into a variable
Besides allowing you to assign a value to a variable, the shell lets you to specify a value for a
variable by using the keyboard. You can enter the value into a variable during the execution of
a shell script by using the read command.
$ read name
On execution the read command waits for you to enter a value for the variable. When you
press the <Enter> key after entering a value, the remaining part of the shell script, if any is
executed. The read command doesn‘t prompt you to enter data. But you can use echo
command to display a prompt.
SJAHER,MOOLAMATTOM Sigma Sathyan
$ echo ―enter your name ― 95
$ echo $name
Annu
Unchanging Variables
If we want that variable a ‗s value should always remain 20 and not changed, you can use:
$ a=20
$ readonly a
When the variables are made readonly the shell doesn‘t allow us to change their values. All
such variables can be listed by entering readonly the $ prompt.
Wiping Out Variables
Variables can be made to cease existing. If we want the shell to forget about a variable
altogether, we use the unset command.
$ unset b
On issuing such command will remove variable b and its values assigned are erased from
shell‘s memory. But we cannot issue:
$ unset PS1
Because if PS1 is unset then there will be no system prompt left for you to issue any
commands.
Exporting variables
By default any variable is available only in the shell in which it is defined. The following
sequence of commands shows this:
$ a=20
$ sh
$ echo $a
$ exit exit from the child shelll
$ echo $a
20 defining a, we invoked a sub shell by using sh at the prompt. We can leave this sub shell
After
by saying exit or Ctrl d.
SJAHER,MOOLAMATTOM Sigma Sathyan
96
Since variable „a‟ was defined in its parent shell, it has no identity in child shell. But when we
leave the child shell we can make „a‟ alive. If we want variables to be available to all sub
shells we create we have to export them from the parent shell.
$ a=20
$ export a
$ echo $a
20
$ sh
$ echo $a
20
$ a=12
$ echo $a
12
Press ctrl d displays exit and returns to parent shell
$ exit
$ echo $a
parent shell continues to have the value 20
20
To obtain a list of all exported variables we use export at the shell prompt.
$ export
Note:
a) A variable once exported from the parent shell becomes available to the sub shell or any
other shells launched from this sub shell. This so happens because whenever a sub shell is
executed, the lists of exported variables get copied to the sub shell, while the local
(unexported) variables in parent shell does not.
b) Once a variable is exported it remains exported to all sub shells that are subsequently
executed.
c) We can first create the variable and then export it or first export it and then create it.
export a b c
a=100 b=200 c=300
is same as
export a b c
d) A variable once exported remains exported. If we are to unexport it we must first unset it
and then recreate it.
e) A variable can be exported from the parent shell to its sub shell, but reverse is not true.
Thus if we create a variable ‗b‘ in a sub shell and then export it, it would not become available
to the parent shell.
f) If the sub shell changes the value of exported variables the value of this variable in the
parent shell remains unchanged since the sub shell always works on the copy of the variable
in the parent shell.
g) If an exported variable is modified in a sub shell then to make this modified value available
to a sub shell once again export the variable in the sub shell.
Shell Programs
1) Program to display a hello message
$ vi pgm1
#!/bin/bash
echo ―hello how are you‖
:wq
$ chmod u+x pgm1
$ ./pgm1
OUTPUT
hello how are you
:wq
$ sh user.sh
98
OUTPUT
user is : arun
Today is Sat Feb4 20:09:43 EST 2012
number of user login : 4
The command expr is used to perform arithmetic operations. Its syntax is as follows:
If you assign a string to a variable then try to add 1 to it, you will not get the result:
$ x=‖hello‖
$ y=`expr $x + 1`
expr: non numeric argument
$
Arithmetic Expansion
To calculate the value of an expression you can enclose the expression in $ ( ( ….. ) )
Example:
$ echo $ ( ( 45 + 34 ) )
79
$ a=12
99
$ b=10
$ echo $ ( ( a + b ) )
22
Shell program to print the total number of unanswered queries in a BPO company
$ vi call.sh
echo ―Enter the total number of calls reported today : ―
read total
echo ―Enter total number of answered calls : ―
read ans
unanswered=$ ( ( total – ans ) )
OUTPUT
$ sh call.sh
Enter the total number of calls reported today : 120
$ vi mesg
#!/bin/bash
echo ―Your name please : ―
read fname
echo ―Hello $fname , We are friends‖
OUTPUT
$ chmod u+x mesg
$ ./mesg
Your name please : Amitha
Exit status
By default in Linux if a particular command or script is executed it returns two types of values
100
which is used to show whether the command or script is successful or failure. This value is
called exit status. If the value returned is zero, command or script is successful. If the value
returned is non zero, command or script is failure. To print that value use $? with the echo
command.
Examples:
1)$ rm test
rm : cannot remove test: no such file or directory
$ echo $?
2
Syntax:
command1;command2
Examples:
Will print today's date followed by users who are currently login.
$ date;who
Wild card
Meaning Examples
/Shorthand
$ ls * will show all files
[...] one of the $ ls [abc]* will show all files beginning with letters a,b,c
enclosed
characters
Note:
[..-..] A pair of characters separated by a minus sign denotes a range.
Example:
$ ls /bin/[a-c]*
Will show all files name beginning with letter a,b or c like
But
$ ls /bin/[!a-o]
$ ls /bin/[^a-o]
If the first character following the [ is a ! or a ^ ,then any character not enclosed is matched
i.e. do not show us file name that beginning with a,b,c,e...o, like
The if condition is used in decision making in shell script. If the given condition is true, the
command is executed otherwise won‘t. Condition is the comparison between the values. For
example, you have seen in some websites, ―Enter only if you are 18+‖. If you click on Yes
you can enter into the website and if you click No you won‘t be allowed to enter the website.
The expression that will be used in shell scripting are:
1. ―-gt‖ = Greater than
3. ―-eq‖ = Equals to
Syntax
test <expression>
or
[ expression ]
The test command can carry out several types of tests. These are:
Operator Meaning
Numerical Test
If his basic salary is less than Rs. 1500, then HRA = 10% of basic salary and DA = 90% of
basic. If his salary is either equal to or above Rs. 1500. then HRA = Rs. 500 and DA = 98% of
basic salary. If the | employee's salary is input through the keyboard write a program to find
his gross salary.
Program:
read bs
then
else
hra=500
fi
gs=`echo $bs + $hra + $da | bc`
File Test
The test command has several options for checking the status of a file. These are shown
below. Using these we can find out whether the specified file is an ordinary file or a directory,
or whether it grants read, write or execute permissions, so on and so forth.
Option Meaning
-s file True if the file exists and has a size greater than 0
else
echo ―what you entered is not a file name‖
fi
105
Let us write another program on similar lines. This one checks whether the user has write
permission to a file. If yes, it prompts the user to type a message which then gets appended to
the mentioned file.
echo “Enter file name”
read filename
if [ -w $filename ]
then
echo “Type matter to append. To stop type Ctrl D.”
cat » $filename
else
echo” No write permission.”
If the
fi user has a write permission to the filename supplied from the keyboard, the matter typed
by the user is read by the cat command and then using redirection operator (») gets appended
to the desired file. When the user hits Ctrl d the cat command comes to an end.
String Tests
Another set of tests that the test command can handle are the string tests. The checks that we
can carry out using these tests are shown below:
Condition Meaning
Program:
str1="Good"
str2="Bad”
str3=
[ $str1 = $str2 ]
echo $?
106
[ $str1 ! = $str2 ]
echo $?
[ -n $str1 ]
echo $?
Output
1
0
0
Can you figure out what will output of the following program?
Program:
str1=‖good morning‖
str2=‖good bye‖
[ $str1 = $str2 ]
echo $?
OUTPUT
test: unknown operator morning
Since two word strings are being assigned to variables str1 and str2 we have taken care to
enclose the strings within a pair of double quotes. But the test failed. Look at error message
and you would be able to understand the reason: The test command went to work with [ good
morning = good bye]. Naturally, morning was treated as an operator, hence the error. If you
write the test as
[ ―$str1‖ shown below
= ―$str2‖ ] the error won‘t occur:
1) IF-THEN-FI STATEMENT:
fi
If the user enters the age greater than or equals to 18 he/she will be prompted will the message
―You are allowed to enter‖ and If the user enter the number less than 18 the program will exit.
Let me show you the output.
2) IF-THEN-ELSE-FI STATEMENT:
read age
if [ ―$age‖ –lt 13 ] || [ ―$age‖ –ge 60 ];
then
echo ―Invalid choice‖
elif [―$age‖ –ge 13 ] || && [ ―age‖ –lt 19 ];
then
echo ―Teenager‖
echo ―Youth of the nation‖
elif [ ―$age‖ –ge 20 ] && [ ―$age‖ –lt 25 ];
fi
then
4) Nested if-else-fi Statement
We can write an entire if-else-fi construct within either the body of the if statement or the
body of an else statement. This is called ‗nesting‘ of ifs. Syntax is as follows:
then
if condition
if condition
then
…..
…..
else
…..
do this
fi
else
…..
do this
fi
Example:
choice=0
echo ―1. Ubuntu Linux‖
echo ―2. Suse Linux‖
echo –n ―Select the choice [1 0r 2]?‖
read choice
if [ $choice –eq 2 ]; then
if [ $choice –eq―you
echo 1 ]; then
pick up Suse Linux‖
echo ―you
else pick Ubuntu Linux‖
else #### nested
fi echo if-elses choice‖
―Invalid ie, if within if ###
fi
109
STATEMENT.
#!/bin/sh
echo "Enter the age of your child: c"
read age
if test $age -le 1
then
echo "Use mother's milk"
elif test $age -le 5
then
echo "Baby is growing up"
elif test $age -le 10
then
echo "Really grown up"
else
echo "**Age should be less than or equals to ten only**"
fi
This is a simple script. See the output below.
110
case statement
The case statement is a good alternative to multilevel if-then-else-fi statement. It enables you
to match several values against one variable. Syntax is as follows:
case $variable_name in
option 1) command
…..
…..
command;;
option 2) command
…..
…..
command;;
option N) command
…..
…..
command;;
*) command
…..
…..
esac command;;
The $variable_name is compared against the patterns until a match is found. The shell then
executes all the statements up to the two semicolons that are next to each other. The default is
*) and it is executed if no match is found.
Example:
echo ―enter a number from 1 to 3 : ―
case $num in
read
1)num echo ―you entered 1‖
;;
echo ―you entered 2‖
2)
;;
echo ―you entered 3‖
3)
;; *) echo ― I said 1 to 3 !‖
;;
esac
111
LOOPS (Iteration Constructs in Linux)
A loop involves repeating some portion of the program either a specified number of times or
until a particular condition is being satisfied. There are three methods by which we can repeat
a part
a) of a using
program.
a forThey are:
statement
b) using while statement
c) using until statement
The for loop
Syntax:
do
execute one for each item in the list until the list is
done
do
..... ...
done
In above syntax BEFORE the first iteration, expr1 is evaluated. This is usually used to
initialize variables for the loop. All the statements between do and done is executed repeatedly
UNTIL the value of expr2 is TRUE. AFTER each iteration of the loop, expr3 is evaluated.
This is usually used to increment a loop counter.
$ cat > for2
for (( i = 0 ; i <= 5; i++ ))
do
echo "Welcome $i times"
done
Run the above script as follows:
$ chmod +x for2
$ ./for2
Welcome 4 times
Welcome 0 times
Welcome 5 times
Welcome 1 times
In above example, first expression (i = 0), is used to set the value variable i to zero. Second
Welcome 2 times
expression is condition i.e. all statements between do and done executed as long as expression
Welcome 3 times
2 (i.e continue as long as the value of variable i is less than or equal to 5) is TRUE. Last
The while loop
expression
Syntax: i++ increments the value of i by 1 i.e. it's equivalent to i = i + 1 statement.
while < condition>
do
< commands s >
done
113
In the while construct, the commands to be executed are specified within the do and done
keywords. The do and done are used to delimit commands in an iteration construct. The
commands within the do and done keywords are executed as long as the condition evaluates to
true.
Example:
count=1
while [ $count –le 3 ]
do
echo ― enter values for p, n, r : ―
read p n r
si=‘echo $p \* $n \* $r / 100 | bc‘
echo ―simple interest = Rs $si ―
Conditional
count=‘exprwhile
$countloop
+ 1‘exit with break statement
You can do early exit with the break statement inside the while loop. You can exit from
done
within a WHILE using break. General break statement inside the while loop is as follows:
while [ condition ]
do
statements1 #Executed as long as condition is true and/or, up to a disaster-condition if
any.
statements2
if (disaster-condition)
then
break #Abandon the while lopp.
fi
statements3 #While good and, no disaster-condition.
done
In this example, the break statement will skip the while loop when user enters -1, otherwise it
will keep adding two numbers:
#!/bin/bash
while :
do
read -p "Enter two numnbers ( - 1 to quit ) : " a b
114
if [ $a -eq -1 ]
then
break
fi
ans=$(( a + b ))
while [ condition ]
do
statements1 #Executed as long as condition is true and/or, up to a disaster-condition if
any.
statements2
if (condition)
then
continue #Go to next iteration of I in the loop and skip statements3
fi
done
statements3
You can use : special command with while loop to tests or set an infinite loop or an endless
loop. An infinite loop occurs when the condition will never be met, due to some inherent
characteristic of the loop. There are a few situations when this is desired behavior. For
example, the menu driven program typically continues till user selects to exit his or her main
menu (loop). To set an infinite while loop use:
1. true command - do nothing, successfully (always returns exit code 0)
2. false command - do nothing, unsuccessfully (always returns exit code 1)
3. : command - no effect; the command does nothing (always returns exit code 0)
Syntax
#!/bin/bash
# Recommend syntax for setting an infinite while loop
while : 115
do
echo "Do something; hit [CTRL+C] to stop!"
done
Use the true command to set an infinite loop:
#!/bin/bash
while true
do
done
Note the first syntax is recommended as : is part of shell itself i.e. : is a shell built-in
command.
The until loop
SYNTAX
The until loop continues running commands as long as the item in list continues to evaluate
true. Once an item evaluates false, the loop is exited. The syntax is:
until [ condition ]
do
command1
command2
...commandN
done
....
116
Welcome 1 times.
Welcome 2 times.
Welcome 3 times.
Welcome 4 times.
Welcome 5 times.
Welcome
The loop in 6thetimes.
above example initializes the variable i to 1, and then increments and displays
out the message until it equals 6.
Functions
When program gets complex we need to use divide and conquer technique. It means whenever
programs get complicated, we divide it into small chunks/entities which are known
as function.
Function is series of instruction/commands. Function performs particular activity in shell i.e.
it had specific work to do or simply say task.
Why to write function?
117
1)Saves lot of time.
2)Avoids rewriting of same code again and again
3)Program is easier to write.
4)Program maintains is very easy.
You can pass the parameter i.e. command line option to function as you passed to shell script.
As you know you can define the function as follows:
function function-name( )
{
statement1
statement2
} statementN
.
118
119
if [ ―$1‖
And you –gt 1this
can call ]; function
then (without command line option) within the shell script as
follows:
Next=`expr $1 – 1`
function-name
Rec=`fac $next`
Prod=`expr
You can pass the$1 \* $Rec`to function i.e. command line option to function as follows:
parameter
echo $Prod
function-name arg1 arg2 arg3 argN
else
fi
To
} clear you1 idea lets write shell script:
echo
echo ―enter a number :‖
$ vi pass
read
echo num
―$num!= `fac $num`‖
function demo()
{
How
echo to de-bug"Allthe shell script?
Arguments to function demo(): $*"
While programming shell sometimes you need to find the errors (bugs) in shell script and
echo "First argument $1"
correct the errors (remove errors - debug). For this purpose you can use -v and -x option with
echo "Second argument $2"
sh or bash command to debug the shell script. General syntax is as follows:
echo "Third argument $3"
sh
Syntax: option { shell-script-name }
return
#
OR
}# optionCall { the shell-script-name function}
bash can
# be
Option shell input lines as are
demo -f foo bar they read.
-x Run
After expanding
the each simple-command,
above bash displays thescript
shell expanded value as of PS4 system
follows:
-v Print
variable,
$ followed by the commandchmod and its expanded arguments.+x pass
Example:
$All ./pass
$ Arguments to
cat function demo():
> -f foo dsh1.sh
First argument -f
bar
#
Second Script to show
argument debug of foo
shell
#Third argument bar
As #you can see the demo() function is$1
define at the beginning of shell
+ script. As you refer the$2`
command line args/option for shell script, same way you can refer the parameter for function.
tot=`expr ctrl
To Press
pass the parameter +
demo to functiond
-f we towrite itsave, and
as followsrunin shellitscript:bar
statement foo as
echo $tot chmod 755
This$ statement passes three parameter to function demo -f, foo and bar. All of these dsh1.sh
./dsh1.sh 4
$9
parameters are stored to $1, $2, and $3 variable of function demo(). 5
++ expr 4 + 5
+ tot=9
$tot
echo echo
9 + 9
See the above output, -x shows the exact values of variables (or statements are shown on
screen with values).
Use
$ sh -v -v option4to5 debug complex shell script.
dsh1.sh
Positional Parameters
Special built-in environmental variables are positional parameters which hold command-line
arguments to positions with the names 1,2,3,4, etc. which are indicated by $1,$2,$3,$4, etc.
Argument $0 is the name of the script. These parameters are named positional because
within the script the reference is to the position they occur on the command line.
These positional variables can be used by a script. Those used typically are variables $0-$9
and $#. Once you have created a script and you name and execute the script you can begin
using these positional parameters. For a script named param.sh, when you call the script you
can follow the script name with variables. Here is an example:
sh param.sh server mail
In this example the script is called param.sh so that is the first parameter ―$0‖ which is
automatically used. Then the next 9 parameters can be entered on the command line. Here
the first parameter is ―server‖ ―$1‖ and the second parameter is ―mail‖ ―$2‖.
sh param.sh server mail
Call with 2 parameters
The Shell Script Name is param.sh
$# number of parameters
The
$0 first parameter
script nameis server
$1-9second
The parameters
parameterbyisposition
mail entered
$@ thirdlist
The all parameters
parameter is used (places arguments on separate lines)
$*
All list all parameters
parameters
#!/bin/bash are serverused
mail(places arguments on one line separated by spaces)
Here
echois“Call
the actual
with script and a list of how to use the parameters.
$# parameters”
echo “The Shell Script Name is $0″
echo “The first parameter is $1″
echo “The second parameter is $2″
echo “The third parameter is $3″
echo “All parameters are $@”
121
The parameters that you enter are picked up and used by the script; these can vary every time
you use the script. So if you create the script the output of these two examples will each be
different because the positional parameters are different.
sh param.sh wokstation tech research
sh param.sh server web apache
You can use the built in command set to assign values of the arguments for the positional
parameters. The set command is a built in command that can be used with ―-o‖ to turn a bash
feature on and ―+o‖ to turn a feature off. At times the set command can be used inside a script
to assign values to variables. Here is a simple script that illustrates the point. Here called with
no parameters and called with one parameter the output is the same because they have been
assigned values.
Sciptname param2.sh
#!/bin/bash
setnetwork
server ipipnetwork
server
echo $3 $2
These $1
positional parameters are very useful when using them in scripts.
sh param2.sh
network ipParameters
Positional server
sh param2.sh
They 2 variables defined by the shell. They are nine in number named $1 through
are special
$9.Setting Values of Positional Parameters
To assign values to the positional parameters – use the set command.
$ set Friends come and go, but enemies accumulate
The above command sets the value $1 with 'Friends', $2 with 'come' and so on. To
verify, we use the echo statement to display their values.
Friends come and go, but enemies accumulate
On$giving
echo $1 $2 $3set
another $4command,
$5 $6 $7 the old values of $1, $2, etc are discarded and the new values
get collected.
$ set Do you want credit or results
$ set A smiling face is always beautiful
$ echo $1 $2 $3 $4 $5 $6
A smiling face is always beautiful
Had we echoed the values of $l through $6 before issuing the second set command obviously
the results would have been different.
Let us now see another way of setting values in positional parameters. Suppose we have typed
the line 'Give luck a little time and it will surely change' in a file called 'lucky'. We can make
122
set take the values to be assigned to positional parameters from this file by saying,
$ set `cat lucky`
$ echo $1 $2 $3 $4 $5
Give luck a little time
Whenever the quoting metacharcter `` are used the command given within `` is replaced by
the output of the command. In our case `cat lucky` got replaced by Give luck a little time and
it will surely change. Hence set used this sentence to set up the positional parameters as the
output of the echo command would justify. The characters `` are called reverse quotes or
more correctly ―accent graves‖.
Displaying Date in Desired Format
The date command by default displays the current date and time in the following format:
Fri Apr 19 11:30:45 IST 1996
To display the information in any order like:
Fri 19 Apr 1996
We can use the set command as follows:
$ vi pos.sh
set `date`
echo $1 $3 $2 $6
:wq
$sh pos.sh
Output
Fri 19 Apr 1996
Using Shift on Positional Parameters
We have used the set command to set up to 9 words. But we can use it for more.
$ echo
$ set You $1 $2 the
have $3 $4 $5 $6 $7
capacity to $8 $9 from mistakes. You will learn a lot in your life.
learn
mistakes.
$echo You$4will
$1 $2 $3 learn
$5 $6 $7 a$8
lot$9in$10
your$11
life.
Now where have the first seven words gone? They have been shifted out. Each word vacated a
You have the capacity to learn from mistakes. You You0 You1
position for the one on its right with the first word getting lost in the bargain. This occurred 7
Observe the last two words in the output. These occurred in the output because at a time we
times; hence we find the last 9 words in $1 through $9. The first seven are lost forever, as we
can access only 9 positional parameters. When we tried to refer to $10 it was interpreted by
did not take the precaution to store them elsewhere. To prevent the loss we should have done:
the shell as if you wanted to output the value of $1 and a 0. Hence we got YouO in the output.
$ set You have the capacity to learn from mistakes. You will learn a lot in your life.
$ b=$2
Same is the story with $11. It doesn‘t mean that words following the ninth word have been
$ a=$1
lost. They are safe with the shell. But to reach them we must do the following.
$ shift 7
123
$ c=$3
$ d=$4
$ e=$5
$ f=$6
$ g=$7
$ echo $a $b $c $d $e $f $g $1 $2 $3 $4 $5 $6 $7 $8 $9
$ shift 4
You have the capacity to learn from mistakes. You will learn a lot in your life.
We can employ an easier method.
$ set You have the capacity to learn from mistakes. You will learn a lot in your life.
$echo $*
You have the capacity to learn from mistakes. You will learn a lot in your life.
Here $* stands for all positional parameters, including those beyond $9. This means that
using $* we can access all the parameters taken together but not individually. The
following example would further clarify this concept.
$ vi pos2.sh
set If you are headed in the wrong direction, God allows U turns.
echo $*
shift 1
echo $*
shift 1
echo $*
echo $*
And here is the output you would get when you execute it...
shift 1
If you are headed in the wrong direction, God allows U turns.
echo $*
you are headed in the wrong direction, God allows U turns.
shift
are headed In the wrong direction, God allows U turns.
headed in the wrong direction, God allows U turns.
Observe
in thethe last direction,
wrong shift command in the program.
God allows U turns. Here we have not mentioned the number of
parameters to be shifted. When we do not do so, by default 1 parameter is shifted.
UNIT V
124
Simple Filter Commands – pr, head, tail, cut, sort, uniq, tr
Filters
A filter is programs that takes input from the standard input file, process it and sends the
output to the standard output file. Linux provides various filters like cat, grep, wc, tr cut etc to
enable you to work effectively with data
Filters Purpose
cat Concatenates and displays files
pg Paginates display for terminals
more
Displays a file one screenful at a time
head
Prints the first few lines of a file
tail
Displays the last few lines of a file
grep Sorts and merges files
Searches
Adds linefiles for a to
numbers pattern
a file
sort
pr Prints files to the standard output
nl
wc Counts lines, words and characters
tee
Creates a tee in a pipe
uniq Reports repeated lines in a file
tr Translates characters in a file
cut
Cuts out selected fields of each line of a file
paste
Mergesrequests
Sends lines oftofiles
line printer
lpr
tr - translate or delete characters. Translate, squeeze, and/or delete characters from standard
input, writing to standard output. Note that this command gets input from the standard input
(keyboard), not from a file. But you can use pipe or redirection to use a file as input.
tr <Character_Set1><Character_Set2><StandardInput>
[mca@chavara amitha]$ cat >e2.txt
computer
zoology
commerce
botany
physics
[mca@chavara amitha]$ cat e2.txt | tr "[a-z]" "[A-Z]"
COMPUTER
ZOOLOGY
COMMERCE
BOTANY
PHYSICS
[mca@chavara amitha]$ tr "c,o" "C,O" < e2.txt
COmputer
zOOlOgy
COmmerCe
bOtany
physics
The tr command used with –d option deletes the characters specified in <character_set> from
input, doesn‘t translate.
[mca@chavara amitha]$ tr -d "c,o" < e2.txt
mputer
zlgy
mmere
btany
physis
uniq
It is used to handle duplicate lines in a file. If this command is used without any option, it
displays the lines by eliminating duplicates lines.
Syntax:
$ uniq –options filename
Options used are:
-u displays only the non repeated lines
-d displays only the duplicated lines
-c displays each line by eliminating duplicate lines and prefixing the number of times it
occurs.
2 bb
Examples:
2 bb
$ cat emp
SJAHER,MOOLAMATTOM SIGMA SATHYAN
1 aa
126
3 cc
4 dd
4 dd
4 dd
5 ee
6 ff
6 ff
$ uniq emp
1 aa
2 bb
3 cc
4 dd
5 ee
6 ff
$$ uniq
uniq –d
–u emp
emp
21 bb
aa
43 dd
cc
65 ff
ee
$ uniq –c emp
1 1 aa
2 2 bb
1 3 cc
2 6 ff
3 4 dd
Refer notes of unit 1, 2 for commands : head tail cut sort pr
1 5 ee
Filters Using Regular Expressions: grep, egrep, sed
In the simplest terms, grep (global regular expression print) is a small family of commands
that search input files for a search string, and print the lines that match it. Although this may
not seem like a terribly useful command at first, grep is considered one of the most useful
commands in any Unix system. Grep is made up of three separate, yet connected commands,
grep, egrep, and fgrep, a sort of holy trinity of Unix commands. All three of the grep
commands work the same way. Beginning at the first line in the file, grep copies a line into a
buffer, compares it against the search string, and if the comparison passes, prints the line to
the screen. Grep will repeat this process until the file runs out of lines. Notice that nowhere in
SJAHER,MOOLAMATTOM SIGMA SATHYAN
this process does grep store lines, change lines, or search only a part of a line.
127
grep is an acronym for ‗globally search a regular expression and print it‘. The command
searches the specified input fully (globally) for a match with the supplied pattern and displays
it. While forming the patterns to be searched we can use shell meta charters or regular
expressions like ‗‘ ? [ ] !
The most useful grep flags are shown here:
Options Meaning
-i Ignore uppercase and lowercase when comparing.
-v Print only lines that do not match the pattern.
-c Print only a count of the matching lines.
-n Display the line number before each matching line.
-l Prints only the filenames of files in the query that have lines that match the search
string.
-w Checks if the given pattern is a word by itself and not a part of another word.
-r Checks for the given pattern, recursively within the directory that you specify after
the –r option.
When grep performs its pattern matching, it expects you to provide a regular expression for
the pattern. Regular expressions can be very simple or quite complex, so we won't get into a
lot of details here. Here are the most common types of regular expressions:
Regular Expression Meaning
abc Match lines containing the string "abc" anywhere.
^abc Match lines starting with "abc."
abc$ Match lines ending with "abc.
a..c Match lines containing "a" and "c" separated by any two characters
(the dot matches any single character).
a.*c Match lines containing "a" and "c" separated by any number of
characters (the dot- asterisk means match zero or more characters)
Examples:
2) To search the word picture in two files $ grep picture file1 file2
3) For a search pattern consisting more than one word, single quotes can be used to enclose it
5) To display all four letter words whose first letter is ‗b‘ and last letter ‗k‘. The two ??
symbols denotes one character each. Thus lines containing words like book, back, beak etc
will be listed. $ grep b??k myfile
6) To display all lines that do not contains words starting with ‗a‘. $ grep –v a* myfile
A dot [.] is an important special character. It matches everything except the newline character.
Example:
This searches for lines with 8 at the second position and anything as the first character.
Sets can also be inverted by starting the set description with "[^" rather than "[".
The dot matches everything except new line. It is the same as [^\n]. Where \n is the newline
character.
To match all lines that DO NOT START with a 1 we write -
or
egrep ‗^[^1]' telephone.txt
Regular expressions also come into play when using vi, sed, awk, and other Unix commands.
If you want to master Unix, take time to understand regular expressions. Here is a sample
poem.txtfile and some grep commands to demonstrate regular-expression pattern matching:
Mary had a little lamb
Mary fried a lot of spam
Jack ate a Spam sandwich
Jill had a lamb spamwich
To print all lines containing ‘spam’ (respecting uppercase and lowercase), enter
grep 'spam' poem.txt
Mary fried a lot of spam
Jill had a lamb spamwich
To print all lines containing ‘spam’ (ignoring uppercase and lowercase), enter
grep -i 'spam' poem.txt
Mary fried a lot of spam
Jack ate a Spam sandwich
Jill had a lamb spamwich
To print just the number of lines containing the word ‘spam’(ignoring uppercase and
lowercase), enter
grep –i -c 'spam' poem.txt
3
To print all lines not containing ‘spam’(ignoring uppercase and lowercase), enter
grep -i -v 'spam' poem.txt
Mary hadall
To print a little
lines lamb
starting with ‘Mary’, enter
grep '^Mary' poem.txt
Mary
To hadalla lines
print little lamb
ending with ‘ich’, enter
grep 'ich$' poem.txt
Jack ate a Spam sandwich
Jill had a lamb spamwich
To print all lines containing ‘had’ followed by’ lamb’, enter
grep 'had.*lamb' poem.txt
Mary
Jill hadhad a little
a lamb lamb
spamwich
To print only those lines containing matches that form whole words you can use –w option
with grep.
grep –w ―fried‖ poem.txt
Note:
Mary fried a lot of spam
Now that we have skimmed over the basic functions of the commands in the grep family, we
can look at a few examples of more advanced functionality. The following example is an
example of grepping through the output of another program rather than a file. This particular
example will print out the files that find returns that contain the text "hello" (although this
$ find | grep "hello"
could be done without using grep at all)
Normally, grep does not have a way to search through portions of files, but when the file is
first processed by another program, this is possible. This example performs a grep on the last
8 lines
$ tailof-n8
file1.
file1 | grep "boo"
By using the exec switch with the find command, we can find files that contain the search
string. The following will search for the string "boo" in every directory below the current
directory
$ find . -exec grep "boo" {} \;
grep is the only command of the three that supports back references and saving. The
following uses back references to find lines that contain two of the same lowercase letter in
succession.
$ grep "\([a-z]\)\1" file1
While grep supports a handful of regular expression commands, it does not support certain
useful sequences such as the + and ? operators. If you would like to use these, you will have to
use extended grep (egrep). Egrep is equivalent to grep -E, but as it is fairly common to want
the extended functionality, egrep is also its own separate command. The Following command
131
It is a program which scans a specified file line by line and returns lines that contain a pattern
matching a given regular expression.
EXAMPLES
To specify a set or range of characters use braces. To negate the set, use the hat symbol ^ as
the first character. For example
1. [a9A05] is the set { a, 9, A, 0, 5 }
2. [^a9A05] is the complementary set ASCII - { a, 9, A, 0, 5 } (everything except a, 9, A,
0 and 5).
3. [a-z] is the set of all lowercase letters { a, b, c, d, ..., z }
4. [^a-z4-9QR] is the set of all ASCII letters except for the lowercase letters, the numerals
between 4 and 9, and the uppercase letters Q and R.
Multipliers
A multiplier determines how often a single character pattern must occur in the text.
Description grep egrep
zero or more times * *
one or more times \{1\} +
zero or one time \? ?
n to m times \{n,m\}
To match a line that starts with a 1, has some digits, at least one space and a name that starts
with a K we can write:
$ grep '^1[0-9]\{1,\} \{1,\} K‘ phonelist.txt
or
$ grep ‗^1[0-9] [0-9]* *K' phonelist.txt
Or
/\
Multiplier
$ egrep ‗is1used to +K'
[0-9]+ multiply the occurrence of the preceding single character pattern. So
phonelist.txt
―12*3‖ does not mean ― 1 then 2 anything 3‖ (this would be 12.*3‖)
Simply it means ―One 1 then there may be Many 2s and One 3‖
Alternation
With the | metacharcter, the or you can merge several regexes into a single regex. With this
you supply the regex engine with alternatives. Jack and Jill are two separate regexes, whereas
jack|jill is one that will match either.
Fgrep
Fgrep is the third member of the grep family. It stands for "fast grep". Fgrep is faster than
other grep commands because it does not interpret regular expressions, it only searches for
strings of literal characters. FGREP is equivalent to grep -F. If we. fgreped for boot|boots,
rather than interpreting that as a search for either the word boot or the word boots, frep would
simply search for the literal string "boot|boots" in the file. For instance, with normal grep the
following command would search for lines ending with the word "broken"
133
# fgrep "broken$" file1
However, we can see that with fgrep, it will return the line "broken$tuff" because it is not
interpreting the dollar sign, only the entire string as literal characters. It is a good practice to
use fgrep instead of grep for situations like these.
fgrep command is used to search one or more files for lines that match the given string or
word. fgrep is faster than grep search, but less flexible: it can only find fixed text, not regular
expressions.
The Syntax is
# fgrep [options] pattern [file]
Options
-a Don't suppress output lines with binary data, treat as text.
-b Print the byte offset of input file before each line of output.
EXAMPLE:
fgrep -i root /etc/passwd Search for root in the file /etc/passwd.
You can use fgrep to find all the lines of a file that contain a particular word. For example, to
list all the lines of a file named myfile in the current directory that contain the word "dog",
enter at the Unix prompt:
134
SUBSTITUTION COMMAND
The "s" command substitutes the text with another.
$ 's/Hello/Hi/g' filename
Here, "g" at the end stands for "global". It means to replace every occurrence on the line. If we
leave it, only the first occurrence on each line will be changed.
REGULAR EXPRESSIONS
1) ‗^‘character means the BEGINNING OF THE LINE.
$ sed 's/^Fri /Friday/' Days.txt
It will turn "Fri" into "Friday", but only at beginning of the line because "g" flag is not used
and therefore we can't have multiple beginnings of a line.
2) The '$' character means the END OF THE LINE.
$ sed 's/ $//' filename
It will replace every space character which occurs at the end of a line.
136
3) Square Brackets "[ ]" specify any one of a number of characters. It is useful when we don't
know whether a letter will be upper or lower case:
$ sed 's/[Hh]i[Gg]ood/higood/g' filename
4) If we want to exclude a set or range of characters, we should use the‘^‘ character as the first
thing inside the brackets:
$ sed `s/ [ ^B-DNM-Y]\. //g` filename
It will delete any middle initials that are not B, C, D. N. M...,Y.
5) A '*' character means "ANY NUMBER OF THE PREVIOUS CHARACTER". It is applied to
literal characters and to characters that are a result of using "[ ]" or '.' .
For example,
$ sed 's/ *$//' filename
It will delete all trailing spaces from each line, WHEREAS
Linux Sed Command : Does Linux Have a Search & Replace Feature?
You can use the sed command to change all occurrences of one string to another within a file,
just like the search-and-replace feature of your word processor. The sed command can also
delete a range of lines from a file. Since sed is a stream editor, it takes the file given as input,
and sends the output to the screen, unless you redirect output to a file. In other words, sed
does not change the input file. The general forms of the sed command are as follows:
Substitution sed 's/<oldstring>/<newstring>/g' <file>
Deletion sed '<start>,<end>d' <file>
The grep command searches the given file for lines containing a match to the given strings or
words. By default, grep displays the matching lines. Use grep to search for lines of text that
match one or many regular expressions, and outputs only the matching lines.
Difference between grep, egrep and fgrep?
grep command is used to search the contents of files that matches a particular criteria.
grep - basic regular expressions
egrep - uses extended regular expressions ( slowest )
fgrep - no regular expressions ( fastest )
138
From this you can understand that both egrep and fgrep functionality can be obtained using
grep command.
egrep can be used to search 2 srings.
Example:
egrep -l "linux|windows" ./*
grep -E -l "linux|windows" ./*
or
The above command will list all the files with the words linux or windows in it.
grep Search a Pattern from current directory.
egrep (grep -E in linux) is extended grep where additional regular expression metacharacters
have been added like +, ?, | and ().
fgrep (grep -F in linux) is fixed or fast grep and behaves as grep but does not recognize any
regular expression metacharacters as being special.
Printing Commands
lpq command:
We can use lpq command to check the status of the print queue. And to view the entries in the
print queue.
lprm command
It is used to remove a print job from the print queue.
-a
Options to remove all the print jobs from the entire print queue available to the
user.
user <user_name> to
-P <printer_name> toremove
remove the
print jobjob
given bythe
specified user.
to remove print
print job from specified printer
job ID with the specified job id
Examples:
$ lprm 8
It will delete the print job with the job id 8 from the default printer.
$ lprm –P ql –U steve
It will delete all the print jobs given by user steve in the ql print queue.
lpc command
It is used by system administrators to control the operations of the print services. You can use
lpc to Disable or enable a printer, Disable or enable the print queue of a printer ,Rearrange the
jobs in a print queue and Check the status of printers their associated print queues and the
printer daemons
139
1. DHCP server
The dynamic host configuration protocol is a network configuration protocol for host on
internet protocol network. Computers that are connected to IP networks must be configured
before they can communicate with other host. The most essential information needed is an IP
address and a default route and routing prefix.
DHCP eliminates the manual task by a network administration. It also provides a central
database of devices that are connected to the network and eliminates duplicate resource
assignments.
In addition to IP address DHCP also provides other configuration information particularly the
IP address,
DHCP was network route on
first defined service or othertrack
a standard service host. DHCP
protocols is used
in RFC 1531for
in IPv4& IPv6.
October 1993 as an
extension to the boot strap protocol. The motivation for extending boot strap protocol was that
boot strap protocol required manual intervention to add configuration information for each
client and did not provide a mechanism for reclaiming dimmed IP addresses. DHCP is useful
because
When a itDCHP
makesconfigured
it easy to add newconnects
client machinestotoa the network.
network the DHCP client sends a broadcast
query requesting necessary information from a DHCP server. The DHCP server manages a
pool of IP addresses and information about client configuration parameters such as default
gateway, domain name, the name servers and other servers. On receiving a valid request the
server assign the computer and IP address a lease time (length of time the allocation in valid)
and other IP configuration parameters such as the subnet mask and the default gateway. The
Depending
query on implementation
is typically the DHCP
initiated immediately server may
after booting havecomplete
and must 3 methods of the
before allocating IP
client can
addresses.
initiate
1) IP based communicate
Dynamic allocation with other host.
2) Automate allocation
3) Static allocation
i. Dynamic allocation
A network administrator assigns a range of IP addresses to DHCP and each client computer
on the LAN is configured to request an IP address from the DHCP server during network
initialization. The request & grand process uses a lease concept with a controllable time
period allowing the DHCP server to reclaim and then reallocate IP addresses that are not
renewed.
140
SQUID is released in July 1996.it is a proxy server and web server. Proxy server is a server
that acts as an intermediary for request from clients seeking resources from other servers. A
client connects to the proxy requesting some service such as a file, connection, web page on
other resources available from a different server. The proxy server evaluates the request
according to its filtering rules. If the request is validated by the filter the proxy server provide
the resource by connecting to the relevant server and requesting the service on behalf of the
Web cache is a mechanism for the temporary storage of web document such as HTML pages
client.
& images to reduce band width image, server load. A web cache stores copies of documents
passing through it. Subsequent request may be satisfied from the cache of certain candies are
met.
SQUID has a wide variety of users from speeding up a web server by caching repeated
request, to caching web, DNS and other computer network look ups for a group of people
sharing network resources to adding security by filtering traffic. Also primarily used for
HTTP & FTP, SQUID includes limited support for several other protocols including TLS
(Transport Layer Security protocol), SSL (Secure Socket Layer) internet gopher and HTTPs
141
(Hyper Text Transfer Protocol Secure it is a combination of HTTP with SSL or TLS
protocol). SQUID was originally designed to run to UNIX like system, but also runs well on
windows based systems. SQUID is free software. It is used by Wikipedia.
Squid is used by 100‘s of internet provides worldwide to provide their users with the best
possible web access. Squid optimize the data flow between client and server improves
Squid can reduce
performance your server
and caches load and improve delivery speeds to clients. Squid can also be
frequently.
used to deliver content from around the world, typing only the content being used.
4) FTP Server
File Transfer Protocol (FTP) is a standard network protocol used to transfer files from one
host to another host over a TCP based network such as the internet. FTP is built on client
server architecture and utilizes separate control and data connections between the client and
server. FTP users may authenticate themselves using a clear text sign in protocol but can
connect
The firstanonymously if the server
FTP client applications is configured
where to command
interactive allow it. line tools implementing standard
commands and syntax. GUI clients have since been developed for many of popular desktop
OS inoperates
FTP use today.
on application layer of the OSI model and is used to transfer files using TCP/IP.
In order to do this an FTP server needs to be running and waiting for incoming request. The
client computer is then able to communicate with the server. This connection called control
connection remains open for the duration of the session with a second connection called the
data connection either opened by the server from its port to a client port (active mode) or
opened by the client to a server port (passive mode) as required to transfer file data. The
5) connection
control Samba server
is used for session administration. That is commands identification and
passwords
Samba exchanged
is free softwarebetween theunder
licensed clientthe
andGNU
serverGeneral
using a telnet
Publiclike protocol.
License. It is developed in
1992. Samba has provided secure stable and fast file and print services for all clients using the
SMB / CIFS protocol. (Server Message Block / Common Internet File System) works as
application layer of the network.
Samba is an important component of integrated linux or unix servers and desktops into active
directory environment. Samba is freely available unlike other SMB/CIFS implementation and
Samba is software that can be run on a platform like Microsoft windows, unix, linux, IBM
allow for interoperability between unix or linux servers and windows based clients.
system 390 and other OS. It uses the TCP/IP protocol that is installed on the host server.
When correctly configured it allows that host to interact with a Microsoft windows client or
server as if it is a windows file and print server.
It is a software package that gives network administrator flexibility and freedom in terms of
Samba is a free software re-implementation of the SMB/CIFS networking protocol, originally
set up configuration and choice of system and equipment.
142
developed by Andrew Tridgell. As of version 3, Samba provides file and print services for
various Microsoft Windows clients and can integrate with a Windows Server domain, either
as a Primary Domain Controller (PDC) or as a domain member. It can also be part of an
Active Directory domain.
Samba runs on most Unix and Unix-like systems, such as GNU/Linux, Solaris, AIX and the
BSD variants, including Apple's Mac OS X Server (which was added to the Mac OS X client
in version 10.2). Samba is standard on nearly all distributions of Linux and is commonly
included as a basic system service on other Unix-based operating systems as well. Samba is
released under the GNU General Public License. The name Samba comes from SMB (Server
FEATURES
Message Block), the name of the standard protocol used by the Microsoft Windows network
file system.
Samba allows file and print sharing between computers running Windows and computers
running Unix. It is an implementation of dozens of services and a dozen protocols, including
the NetBIOS over TCP/IP (NBT), SMB, CIFS (an enhanced version of SMB), DCE/RPC or
more specifically, MSRPC, the Network Neighborhood suite of protocols, a WINS server also
Domain
known suite of protocols
as a NetBIOS which
Name Server includes
(NBNS), theNT
NT Domain Logons, Secure Accounts Manager
(SAM) database, Local Security Authority (LSA) service, NT-style printing service
(SPOOLSS), NTLM and more recently Active Directory Logon which involves a modified
version of Kerberos and a modified version of LDAP. All these services and protocols are
frequently incorrectly referred to as just NetBIOS or SMB. The NetBIOS and WINS protocols
Samba sets up network shares for chosen Unix directories (including all contained
subdirectories). These appear to Microsoft Windows users as normal Windows folders
accessible via the network. Unix users can either mount the shares directly as part of their file
structure using the smbmount command or, alternatively, can use a utility, smbclient (libsmb)
installed with Samba to read the shares with a similar interface to a standard command line
FTP program. Each directory can have different access privileges overlaid on top of the
normal Unix file protections. For example: home directories would have read/write access for
all known users, allowing each to access their own files. However they would still not have
smbd, which provides the file and printer sharing services, and
nmbd, which provides the NetBIOS-to-IP-address name service. NetBIOS over TCP/IP
requires some method for mapping NetBIOS computer names to the IP addresses of a TCP/IP
143
Samba configuration is achieved by editing a single file (typically installed as /etc/smb.conf or
/etc/samba/smb.conf). Samba can also provide user logon scripts and group policy
implementation through poledit.
Samba is included in most Linux distributions and is started during the boot process. On Red
Hat, for instance, the /etc/rc.d/init.d/smb script runs at boot time, and starts both daemons. Samba
Samba includes a web administration tool called Samba Web Administration Tool (SWAT).
6) APPACHE
Apache is the most widely used HTTP-server in the world today. It surpasses all free and
commercial competitors on the market, and provides a myriad of features; more than the
nearest competitor could give you on a UNIX variant. It is also the most used web server for a
Linux system. A web server like Apache, in its simplest function, is software that displays and
serves HTML pages hosted on a server to a client browser that understands the HTML code.
Mixed with third party modules and programs, it can become powerful software, which will
FEATURES
provide strong and useful services to a client browser.
Apache supports a variety of features, many implemented as compiled modules which extend
the core functionality. These can range from server-side programming language support to
authentication schemes. Some common language interfaces support Perl, Python, Tcl, and
PHP. Popular authentication modules include mod_access, mod_auth, mod_digest, and
mod_auth_digest, the successor to mod_digest.
A sample of other features include Secure Sockets Layer and Transport Layer Security
support (mod_ssl), a proxy module (mod_proxy), a URL rewriter (also known as a rewrite
engine, implemented under mod_rewrite), custom log files (mod_log_config), and filtering
support (mod_include and mod_ext_filter).
Popular compression methods on Apache include the external extension module, mod_gzip,
implemented to help with reduction of the size (weight) of web pages served over HTTP.
ModSecurity is an open source intrusion detection and prevention engine for web
applications. Apache logs can be analyzed through a web browser using free scripts such as
AWStats/W3Perl or Visitors.
144
Virtual hosting allows one Apache installation to serve many different actual websites. For
example, one machine with one Apache installation could simultaneously serve
www.example.com, www.example.org, test47.test-server.example.edu, etc.
Apache features configurable error messages, DBMS-based authentication databases, and
content negotiation. It is also supported by several graphical user interfaces (GUIs).
It supports password authentication and digital certificate authentication. Apache has a built in
search engine and an HTML authorizing tool and supports FTP.
Performance
Although the main design goal of Apache is not to be the "fastest" web server, Apache does
have performance similar to other "high-performance" web servers. Instead of implementing a
single architecture, Apache provides a variety of Multiprocessing Modules (MPMs) which
allow Apache to run in a process-based, hybrid (process and thread) or event-hybrid mode, to
better match the demands of each particular infrastructure. This implies that the choice of
correct MPM and the correct configuration is important. Where compromises in performance
need to be made, the design of Apache is to reduce latency and increase throughput, relative to
simply handling
The Apache moreconsidered
version requests, by
thus
theensuring
Apacheconsistent
Foundationand
as reliable processing
providing of requests
high-performance is
within reasonable time-frames.
the multi-threaded version which mixes the use of several processes and several threads per
process. This architecture, and the way implemented in Apache 2.4.0, provides for
performance at least equal to other event-based web servers.
7) TELNET
telnet server is used to login into another system. You can use the telnet command to log in
remotely to another system on your network. The system can be on your local area network or
available through an Internet connection. Telnet operates as if you were logging in to another
system from a remote terminal. You will be asked for a login name and password. In effect,
you are logging in to another account on another system. In fact, if you have an account on
another system,
You invoke the you could
Telnet use with
utility Telnetthetokeyword
log in to telnet.
it. If you know the name of the site you
want to connect with, you can enter telnet and the name of the site on the Linux command
line.
Telnet is a network protocol used on the Internet or local area networks to provide a
bidirectional interactive text-oriented communications facility using a virtual terminal
connection. User data is interspersed in-band with Telnet control information in an 8-bit byte
oriented data connection over the Transmission Control Protocol (TCP).
145
Telnet was developed in 1969 beginning with RFC 15, extended in RFC 854, and
standardized as Internet Engineering Task Force (IETF) Internet Standard STD 8, one of the
first Internet standards.
Historically, Telnet provided access to a command-line interface (usually, of an operating
system) on a remote host. Most network equipment and operating systems with a TCP/IP
stack support a Telnet service for remote configuration (including systems based on Windows
NT). Because of security issues with Telnet, its use for this purpose has waned in favor of
SSH.
The term telnet may also refer to the software that implements the client part of the protocol.
Telnet client applications are available for virtually all computer platforms. Telnet is also used
as a verb. To telnet means to establish a connection with the Telnet protocol, either with
command line client or with a programmatic interface. For example, a common directive
might be: "To change your password, telnet to the server, login and run the passwd
command." Most often, a user will be telnetting to a Unix-like server system or a network
device (such as a router) and obtain a login prompt to a command line text interface or a
character-based full-screen manager.