Ulp Final
Ulp Final
Ulp Final
Introduction to UNIX/Linux
1.1 What is Linux?
Linux (pronounced Lih-nucks) is a UNIX-like operating system that runs on many
different computers. Linux was first released in 1991 by its author Linus Torvalds at the
University of Helsinki. Since then it has grown tremendously in popularity as
programmers around the world embraced his project of building a free operating system,
adding features, and fixing problems.
Linux is popular with today's generation of computer users for the same reasons early
versions of the UNIX operating system enticed fans more than 20 years ago. Linux is
portable, which means you'll find versions running on name-brand or clone PCs, Apple
Macintoshes, Sun workstations, or Digital Equipment Corporation Alpha-based
computers. Linux also comes with source code, so you can change or customize the
software to adapt to your needs. Finally, Linux is a great operating system, rich in
features adopted from other versions of UNIX. We think you'll become a fan too!
• bash or Bourne Again SHell: the standard GNU shell, intuitive and flexible.
Probably most advisable for beginning users while being at the same time a
powerful tool for the advanced and professional user. On Linux, bash is the
standard shell for common users. This shell is a so-called superset of the Bourne
shell, a set of add-ons and plug-ins. This means that the Bourne Again SHell is
compatible with the Bourne shell: commands that work in sh, also work in bash.
However, the reverse is not always the case.
• csh or C Shell: the syntax of this shell resembles that of the C programming
language. Sometimes asked for by programmers.
To switch from one shell to another, just enter the name of the new shell in the active
terminal. The system finds the directory where the name occurs using the PATH settings,
and since a shell is an executable file (program), the current shell activates it and it gets
executed. A new prompt is usually shown, because each shell has its typical appearance.
System Utilities
Virtually every system utility that you would expect to find on standard implementations
of UNIX (including every system utility described in the POSIX.2 specification) has been
ported to Linux. This includes commands such as ls, cp, grep, awk, sed, bc, wc, more,
and so on. These system utilities are designed to be powerful tools that do a single task
extremely well (e.g. grep finds text inside files while wc counts the number of words,
lines and bytes inside a file). Users can often solve problems by interconnecting these
tools instead of writing a large monolithic application program.
Like other UNIX flavours, Linux's system utilities also include server programs called
daemons which provide remote network and administration services (e.g. telnetd and
sshd provide remote login facilities, lpd provides printing services, httpd serves web
pages, crond runs regular system administration tasks automatically). A daemon
(probably derived from the Latin word which refers to a beneficient spirit who watches
over someone, or perhaps short for "Disk And Execution MONitor") is usually spawned
automatically at system startup and spends most of its time lying dormant (lurking?)
waiting for some event to occur.
Application programs
Linux distributions typically come with several useful application programs as standard.
Examples include the emacs editor, xv (an image viewer), gcc (a C compiler), g++ (a C++
compiler), xfig (a drawing package), latex (a powerful typesetting language) and soffice
(StarOffice, which is an MS-Office style clone that can read and write Word, Excel and
PowerPoint files).
Redhat Linux also comes with rpm, the Redhat Package Manager which makes it easy to
install and uninstall application programs.
At this point, depending on how the system administrator has set things up, you may be
presented with a windows-like (usually X-windows) environment or a simple terminal.
Either way, you should now have a screen where you can type in commands. This is your
shell. Your shell is your interface to the operating system (in DOS, your shell was called
COMMAND.COM). Since UNIX is a multi-tasking as well as multi-user environment, you
can have many shells running at the same time. To further complicate things, there are
several different shells you can use. The default shell on Linux is bash (stands for Bourne
Again SHell). Others include csh, tcsh, ksh and sh. They all serve the same purpose, but each
has different features and syntaxes. As far as this tutorial is concerned, they more or less
work the same, however I will assume you are using bash.
Important: When you are all done, remember to log out of the system. This is usually
accomplished by typing logout at the prompt. If you are using X-Windows, there will be a
large button at the bottom of the screen labeled 'Logout'. You will know you have logged
out completely when you see the login prompt. If you forget to log out, someone else
could come along and mess with your files, or send email from your account!
1.9 LOGOUT
At the command prompt exits your current user account and returns you to the log-in
prompt. The exit command does the same thing as logout. To log out from multiple
consoles, use alt-Fn to switch between consoles and then log out from each one. But note
that even if you log out from all of your active consoles, Linux is still running.
If you really want to exit Linux. Type enter the command
[root@localhost ~]# shutdown -h now
Which effectively goes to run level 0, and
[root@localhost ~]# shutdown -r now
Which effectively goes to run level 6.
Run-level Problem:
Some times the user may change the run-level specified in /etc/inittab file(in the line
id:5:initdefault:)to 0 (or) 6 ,since the run-level 0 is halt and run-level 6 is reboot, the
system will restarts every time you boot or goes to halt
You can increase the number of terminals up to 11.This can be done by following steps
Step 3: Add the line 7:2345:respawn:/sbin/mingetty tty7 and end of the above lines.
Then save and exit from the file and then restart the system
Step 4:After rebooting press ctrl+alt+F7,now you will have 7th terminal. The XWindow
is moved step forward at Ctrl+alt+F8
Likewise you add upto 11 terminals(that is upto ctrl+alt+F11),if you have 11 terminals
then XWindow will be at ctrl+alt+F12
To halt the system once the shutdown is complete, use the `-h' option; to reboot the
system after shutdown, use `-r' instead.
Running commands
Syntax of command: command [options] [args]
Where args are filenames or other data needed by the command.
'-' used with single letter options like -ivh or -i -v -h.
'--'used with words like -- force ,--aid etc.
Each item is separated by a space.
help
This command is used to display usage summary and argument list. It will not display
help for all commands but for most commands help is displayed.
Syntax: <command> --help
man
This command provides documentation for commands. It will display name of command
,short description for it, synopsis of its usage, longer description of commands
functionality ,switch by switch listing of options, files associated with command,
examples and see also section for further reference.
Following 8 sections are available in the man page.
1. Commands This section provides information about user-level commands, such as ps
and ls.
2. UNIX System Calls This section gives information about the library calls that
interface with the UNIX operating system, such as open for opening a file, and exec for
executing a program file. These are often accessed by C programmers.
3. Libraries This section contains the library routines that come with the system. An
example library that comes with each system is the math library, containing such
functions as fabs for absolute value. Like the system call section, this is relevant to
programmers.
4. File Formats This section contains information on the file formats of system files,
such as init, group, and passwd. This is useful for system administrators.
5. File Formats This section contains information on various system characteristics. For
example, a manual page exists here to display the complete ASCII character set (ascii).
6. Games This section usually contains directions for games that came with the system.
7. Device Drivers This section contains information on UNIX device drivers, such scsi
and floppy. These are usually pertinent to someone implementing a device driver, as well
as the system administrator.
8. System Maintenance This section contains information on commands that are useful
for the system administrator, such as how to format a disk.
NAME
cal - displays a calendar
SYNOPSIS
cal [-smjy13] [[month] year]
DESCRIPTION
Cal displays a simple calendar. If arguments are not specified, the
current month is displayed. The options are as follows:
A single parameter specifies the year (1 - 9999) to be displayed; note the year must
be fully specified: “cal 89” will not display a calendar for 1989. Two parameters denote
the month (1 - 12) and year. If no parameters are specified, the current month’s calendar
is displayed.
HISTORY
A cal command appeared in Version 6 AT&T UNIX.
OTHER VERSIONS
Several much more elaborate versions of this program exist, with support
for colors, holidays, birthdays, reminders and appointments, etc. For
example, try the cal from http://home.sprynet.com/~cbag-
well/projects.html or GNU gcal.
info
This command will display pages . Each page is divided into nodes. Links to nodes is
preceded by “*”.
Syntax: info [<command>]
whereis
Tells location of command in the system.
Syntax: whereis <command>
who
This command is used to display who is currently logged on the system.
Syntax: who
who am i
Tells who you are.
Syntax: who am i
cal
This command will display calendar for specified month and year.
Syntax: cal [month] <year>
lpr
This command is used to print one or more files on printer.
Syntax: lpr [options] <file1> <file2>..........
Where options may be
m inform you when printing is over.
r removes files from directory after printing.
Example: Printing a file on printer.
[root@localhost ~]# lpr text.txt
Contents of file text.txt will be printed on printer.
tee
It will send output to standard output as well as specified file. This command perform the
operation of pipe and redirection.
Syntax: <command> | tee <filename>
Example:
[root@localhost ~]# cat text.txt
hello
c
language is a middle level language
C++ is an object oriented language
java is purely object oriented language
[root@localhost ~]# cat text.txt>text1.txt
we can combine these two commands into single command using tee command.
[root@localhost ~]# cat text.txt | tee text1.txt
hello
c
language is a middle level language
C++ is an object oriented language
java is purely object oriented language
history
To display to see list of remembered commands.
Syntax: history [option]
Example:
[root@localhost ~]# history
1 date
2 date
3 pwd
4 ls
5 ls -l
6 ls -l text.txt
7 history
[root@localhost ~]# !3
pwd
/root
Use ^old^ new to repeat last command with old to new
Example:
[root@localhost ~]# cat >text2.txt
hi all
g
[root@192 ~]#
[root@localhost ~]# ^text2.txt^ text3.txt
cat > text3.txt
hi all
who are u
clear
To clear the screen
Syntax: clear
script
This command stores your login session to a specified file. Output is stored in typescript
file .you can also specify any other name of your choice. Exit command is used to finish
the script session.
Syntax: script
expr
This command is used to perform arithmetic operations( operators + for addition,- for
subtraction ,\* for multiplication , % for remainder ,/ for division is used) on integers.
bc
This command is used for activating calculator for performing arithmetic operations on
integers as well as float numbers.
Syntax: bc
Example: Add 10 to 20
[root@localhost ~]# bc
10 + 20
30
Example: Divide 9 by 4
[root@localhost ~]# bc
a=9
b=2
c=a/b
c
4
# bc
obase=2 Set obase to binary
Type the input decimal number
Result in binary
# bc
Ibase =16 Set ibase to hexadecimal
A Type the input hexadecimal number
10 Result in decimal
#bc
Obase =16 Set obase to hexadecimal
11 Type the input decimal number
B Result in hexa-decimal
split
This command is used to split large size file in small size files .Because large size files
cannot be displayed on editor.
Syntax: split -<number> <filename>
Where number is the size of splited files. Default size is 1000 lines. Suppose a file
contains 3550 lines. If we define number size 500. Then large file is splited in 8 files. Out
of them first seven files will be of size 500 lines and last file contains 50 lines. Files will
be named as xaa,xab,xac and so on.
Example: To split a file into different files of size 500 lines each
[root@localhost ~]#split -500 text1.txt
This command will split text1.txt into 500 line files.
To combine the files use following command
[root@localhost ~]#cat x* > newfile
2.3 DIRECTORY ORIENTED COMMANDS IN LINUX
mkdir
This command is used to create a new directory.
Syntax: mkdir <directory-name>
rmdir
This command is used to remove a directory. Directory should be empty before deletion.
Syntax: rmdir <directory-name>
pwd
This command will displays full path name for present working directory.
Syntax: pwd
cd
This command is used for changing current directory to specified directory.
Syntax: cd <directory-name>
Example: To move to a specified directory
[root@localhost ~]# cd dir/dir2
[root@localhost dir2]#
If we use pwd command it will display present working directory as
[root@localhost dir2]# pwd
/root/dir/dir2
ls
This command is used to list the contents of specified directory
Syntax: ls [options] <directory-name>
Options:
Example: Lists all files and directories including hidden files.
-a(All) option is used for this purpose.
[root@localhost ~]# ls -a
. .gnome2 .ssh
.. .gnome2_private .sversionrc
.aaa.sh.swp .gstreamer-0.8 .swp
ani.sh~ .gtkrc t1.doc
.ani.sh.swp .gtkrc-1.2-gnome2 t1.txt
.bash_history .ICEauthority t3.doc
.bash_logout ishan t4.doc
.bash_profile linux book .tcshrc
.bashrc linux slides t.doc
.cshrc naveen .teji.txt.swp
Desktop
Example: Recursively lists all files and directories as well as files in subdirectories
[root@localhost ~]# ls -R dir
dir:
dir1 t4.txt teji.txt
dir/dir1:
t.txt
Example: Displays * after files for those user has executable permission
-F option is used for this purpose
[root@localhost ~]# ls -F teji.doc
teji.doc*
du
Disk usage command reports disk space that is consumed by files in directories including
subdirectories. Without arguments, du reports disk space for current directory.
Syntax: du[options] [<directory-name>]
Options are
Example: Displays output along with grand total of all the arguments
[root@localhost ~]# du -c tejinder
5392 tejinder/teji
5400 tejinder
5400 total
df
Disk free command displays free space available on file system.
Syntax: df [options]
Options are:
Example: shows size in kilobytes
[root@localhost ~]# df -k
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/mapper/VolGroup00-LogVol00
15772060 5262736 9708148 36% /
/dev/sda3 101105 12309 83575 13% /boot
none 123680 0 123680 0% /dev/shm
find
Search a folder hierarchy for filename(s) that meet desired criteria: Name, Size, File Type
etc.
Syntax: find [path...] [options] [tests] [actions]
find searches the directory tree starting at the given pathname (or pathnames if several are
given) by evaluating the given expression from left to right, according to the rules of
precedence, until the outcome is known (the left hand side is false for AND operations,
true for OR), at which point find moves on to the next file name. Conditions may be
grouped by enclosing them in \( \) (escaped parentheses), negated with !, given as
alternatives by separating them with -o, or repeated (adding restrictions to the match;
usually only for -name, -type, or -perm). Note that "modification" refers to editing of a
file's contents, whereas "change" means a modification, or permission or ownership
changes. In other words, -ctime is more inclusive than -atime or -mtime.
The first argument that begins with a - or (or) or, or! is taken to be the beginning of the
expression; any arguments before this are paths to search, and any arguments after it are
the rest of the expression. If no paths are given, the current directory is used. If no action
is given, `-print' is used. find exits with status 0 if all files are processed successfully,
greater than 0 if errors occur.
Example: List all files in those sub-directories (but not the directory names)
[root@localhost ~]# find . -type f
Example: Find files have been modified within the last 30 minutes
[root@localhost ~]#find ~/Directory oriented commands -mmin -30
Example: How do I find all *.c files having 2kb file size?
Syntax : find -size number[ckwb]
number - It's 2 byte or 1 kilobyte etc
c - bytes
k - kilobytes
w - words (2-byte)
b - 512-byte block
[root@localhost ~]# find / -name *.c -size 2k -print
ln
link command is used to establish an additional filename to a specified file. It is not the
duplicate copy. It just likes to call a person with two names.
Syntax: ln <filename> <additional-filename>
Example: creating a new link for a file.
After execution of this command shows number of link for ram.txt
[root@localhost ~]# ls -l ram.txt
-rw-r--r-- 1 root root 33 Dec 14 14:22 ram.txt
After execution of this command we would be able to see contents of ram.txt
[root@localhost ~]# cat ram.txt
hello
india
is
a great country
After execution of this command ram.txt has two links.
[root@localhost ~]# ln ram.txt ram1.txt
Now we are able to see contents of ram.txt with ram1.txt also.
[root@localhost ~]# cat ram1.txt
hello
india
is
a great country
[root@localhost ~]# ls -l ram.txt
-rw-r--r-- 2 root root 33 Dec 14 14:22 ram.txt
cat
Syntax: cat [-Options] [File]...
Options:
-n To number all the lines in a file.
[root@localhost ~]# cat >te.txt
hi all
what is ur name
what abt u?
[root@localhost ~]# cat te.txt -n
1 hi all
2 what is ur name
3
4 what abt u?
3 what abt u?
-T display TAB characters as ^I
Example: To check this option creates a file with tabs.
[root@localhost ~]# cat >t2.txt
c programs are easier to debug as compare to assembly language
What abt c++?
4) Cat command is also used to display contents of multiple files one by one.
[root@localhost ~]# cat teji.txt t.txt
After execution of this command contents of teji.txt and t.txt will be displayed one by
one.
hi i am an indian
hello world
what abt you?
c is a middle level language.
c++ is an object oriented language.
cp
Copy one or more files to another
Syntax: cp [options]... Source Dest
cp [options]... Source... Directory
rm
This command is used to remove a file from a specified directory.
Note:-To remove a file, you must have write permission for directory that contains file.
Syntax: rm [options ] <filename>
mv
Move or rename files or directories. mv can move only regular files across file systems.
Syntax: mv [options]... Source Destination
mv [options]... Source... Directory
If the last argument names an existing directory, `mv' moves each other given file into a
file with the same name in that directory. Otherwise, if only two files are given, it
renames the first as the second. It is an error if the last argument is not a directory and
more than two files are given.
Example: Remove existing destination files and never prompt the user.
[root@localhost ~]# mv -f t5.txt teji.txt
[root@localhost ~]# cat teji.txt
c programs are easier to debug as compare to assembly language
What abt c++?
wc
This command is used to display the number of lines, words and characters of
information stored on the specified file.
Syntax: wc [options] <filename>
Options:
l -Displays the number of lines in a specified file.
w- Displays the number of words in a specified file.
c- Displays the number of characters in a specified file.
comm
This command is takes two files as input and tells what is common .It compares each line
of first file with its corresponding line in second file. It uses three columns
1) Column1 contains line unique to file1.
2) Column2 contains line unique to file2.
3) Column3 contains lines common in file1 and file2.
Syntax: comm [-options] <filename1><filename2>
Options:
1 suppresses listing of column1
2 suppresses listing of column2
3 suppresses listing of column3
cmp
This command compares two files. This compares file byte by byte and displays first
mismatch on the screen.
Syntax: cmp <filename1><filename2>
And the process which manages the Files i.e. creation, deletion, copying of files and
giving read, write access of files to user is called File management.
Example:
[root@localhost ~]# cat> .ramesh.txt
Now if you list the file by using ls -l or ls command you will not be able to see the file.
The hidden folders can also be created in the same manner
Example :
[root@localhost ~]# mkdir .dirname
mkdir is the make directory command and .dirname is your folder name.
File extension
Compressed and Archived Files
.bz2. a file compressed with bzip2
.gz. a file compressed with gzip
.tar. a file archived with tar (short for tape archive), also known as a tar file
.tbz. a tarred and bzipped file
.tgz. a tarred and gzipped file.
.zip. a file compressed with ZIP compression, commonly found in MS-
DOS applications.
File Formats
.au. an audio file
.gif. a GIF image file
.html/.htm. an HTML file
.jpg. a JPEG image file
.pdf. an electronic image of a document; PDF stands for Portable Document
Format
.png. a PNG image file (short for Portable Network Graphic)
.ps. a PostScript files; formatted for printing
.txt. a plain ASCII text file
.wav. an audio file
.xpm. an image file
System Files
.conf a configuration file. Configuration files sometimes use the .cfg extension,
as well.
.lock a lock file; determines whether a program or device is in use
.rpm a Red Hat Package Manager file used to install software
Programming and Scripting Files
.c a C program language source code file
.cpp . a C++ program language source code file
.h . a C or C++ program language header file
.o . a program object file
.pl . a Perl script
.py. a Python script
.so a library file
.sh a shell script
.tcl a TCL script
Operation on files:
Copy file
Delete file
Rename file
Move file
Changing file date & time stamp
Creating symbolic link
Changing file permission or ownership
Searching files
Compressing / Decompressing files
Comparison between files
Printing files on printer
Sorting files etc
Linux users:
user(u):- The user who owns it (u)
user group(g):-Other users in the file's group (g)
Others(o):-Other users not in the file's group (o)
All(a):-All users (a)
Accessing Modes:
Linux contains three types of modes of accessing.
read mode(r):-Permission to read a file or list a directory's contents.
write mode (w):-Permission to write to a file or create and remove files from directory.
execute mode(x):-Permission to execute a program or change into directory.
chgrp
Change group ownership. 'chgrp' changes the group ownership of each given File to
Group (which can be either a group name or a numeric group id) or to the group of an
existing reference file. Before assigning a file to a particular group, group must be exists.
Example: Changing group ownership for a file.
[root@localhost ~]# ls -l ram.txt
---x-w---x 2 kiran root 22 Dec 18 11:27 ram.txt
[root@localhost ~]# chgrp teji ram.txt
After execution group owner of file ram.txt is changed to teji in place of root.
[root@localhost ~]# ls -l ram.txt
---x-w---x 2 kiran teji 22 Dec 18 11:27 ram.txt
chown
This command is used to change ownership of a specified file .super user and owner of
file can change the ownership of file. New owner must be exists in user list.
Syntax: chown <new-owner-name> <filename>
chmod
Change access permissions, change mode. By default, read and write permission is given
to user; only read permission is given to user group and others.
Numeric mode:
Syntax: chmod three-digits-number <file1>................
Use table to allocate permission
Numeric value Octal value Permissions
0 000 No Permission
1 001 Execute Permission
2 100 Write Permission
3 011 Write and execute Permission
4 100 Read Permission
5 101 Read and execute Permission
Numeric value Octal value Permissions
6 110 Read and write Permission
7 111 All Permission
From one to four octal digits any omitted digits are assumed to be leading zeros.
The octal (0-7) value is calculated by adding up the values for each digit
User (rwx) = 4+2+1 = 7
Group(rx) = 4+1 = 5
World (rx) = 4+1 = 5
Examples
chmod 400 file - Read by owner
chmod 040 file - Read by group
chmod 004 file - Read by world
chmod 200 file - Write by owner
chmod 020 file - Write by group
chmod 002 file - Write by world
chmod 100 file - execute by owner
chmod 010 file - execute by group
chmod 001 file - execute by world
To combine these just add the numbers together:
chmod 444 file - Allow read permission to owner and group and world
chmod 777 file - Allow everyone to read, write, and execute file
Symbolic Mode
Syntax: chmod user-symbol set/deny symbol <filenames(s)>
multiple symbolic operations can be given, separated by commas. A combination of the
letters `ugoa' controls which users' access to the file will be changed. If none of these are
given, the effect is as if `a' were given, but bits that are set in the umask are not affected.
all users (a) is effectively
user + group + others
Example: Make a file readable and writable by the group and others:
[root@localhost ~]# chmod go+rw ram.txt
[root@localhost ~]# ls -l ram.txt
---xrwxrwx 2 root root 22 Dec 18 11:27 ram.txt
Example:Allow everyone to read, write, and execute the file and turn on the set
group-ID:
[root@localhost ~]# ls -l ram.txt
---xrwxrwx 2 root root 22 Dec 18 11:27 ram.txt
[root@localhost ~]# chmod rwx,g+s ram.txt
[root@localhost ~]# ls -l ram.txt
-rwxr-sr-x 2 root root 22 Dec 18 11:27 ram.txt
Example: Giving all permissions to others only and detach all other permissions
given group and user.
[root@localhost ~]# chmod a-rwx,o+rwx ram.txt
After execution firstly all permissions are detached from al l(user, group, others).then all
permission are allocated to others.
Important note: Here we will discuss about the 3 special attributes other than the
common read/write/execute.
Example:
drwxrwxrwt - Sticky Bits - chmod 1777
drwsrwxrwx - SUID set - chmod 4777
drwxrwsrwx - SGID set - chmod 2777
Sticky bits: Sticky bits are mainly set on directories. If the sticky bit is set for a directory,
only the owner of that directory or the owner of a file can delete or rename a file within
that directory.
SUID: SUID is set for files (mainly for scripts). The SUID permission makes a script to
run as the user who is the owner of the script, rather than the user who started it.
SGID: If a file is SGID, it will run with the privileges of the files group owner, instead of
the privileges of the person running the program. This permission set also can make a
similar impact. Here the script runs under the group's ownership. You can also set SGID
for directories.
tac
tac command reverses a file, last line becomes first line.
Syntax: tac <filename>
Example: To display contents of a file in reverse order.
[root@localhost ~]# cat >text.txt
hello
c
language is a middle level language
C++ is an object oriented language
java is purely object oriented language
nl
Number lines and write files. It numbers only non-blank lines.
Syntax: nl <filename>
expand
Convert tabs to spaces; write the contents of each given file, to standard output, with tab
characters converted to the appropriate number of spaces. If no file is given, or for a file
of `-', write to standard input
Syntax: expand [options]... [file]...
touch
touch command is used to change last modification and access time of a specified file
into the specified time.
Syntax: touch MMDDHHmm <filename1>..............
Where MM Month(01-12)
DD Day(01-31)
HH Hour(00-23)
mm Minute(00-59)
if MMDDHHmm format is not used then current date and time as taken by default.
Example: To convert last modification and access date and time to current date and
time.
[root@localhost ~]# ls -l dir/t4.txt
-rw-r--r-- 1 root root 77 Dec 14 11:05 dir/t4.txt
[root@localhost ~]# touch dir/t4.txt
[root@localhost ~]# ls -l dir/t4.txt
-rw-r--r-- 1 root root 77 Dec 18 14:20 dir/t4.txt
Example: To convert last modification and access date and time to specified date
and time.
[root@localhost ~]# ls -l dir/t4.txt
-rw-r--r-- 1 root root 77 Dec 18 14:20 dir/t4.txt
[root@localhost ~]# touch -t 08232245 dir/t4.txt
[root@localhost ~]# ls -l dir/t4.txt
-rw-r--r-- 1 root root 77 Aug 23 22:45 dir/t4.txt
Example: To convert last modification and access date and time to specified date
and time of all the file's existing for a particular user.
[root@localhost ~]#touch *
-rw-r--r-- 1 root root 43 Dec 18 14:30 teji1.doc
-rwxr-xr-x 1 root root 3843072 Dec 18 14:30 teji.doc
drwxr-xr-x 3 root root 4096 Dec 18 14:30 tejinder
-rw-r--r-- 1 root root 54 Dec 18 14:30 text1.txt
-rw-r--r-- 1 root root 118 Dec 18 14:30 text.txt
drwxr-xr-x 2 root root 4096 Dec 18 14:30 x
drwxr-xr-x 2 root root 4096 Dec 18 14:30 y
drwxr-xr-x 2 root root 4096 Dec 18 14:30 z
tail
Output the last part of files.
Syntax: tail +/-n <filename>
head
Output the first part of file(s)
Syntax: head -n <filename>
If -n option is used, then first n lines of a file are displayed.
dd
This command copies files and converts them in one format into another.
Syntax: dd[options=values]
Where options can be,
if input filename
of output filename
conv file conversion specification. More than one conversion may be specified
by separating them with commas. The values for this option may be as
follows,
lcase convert uppercase letters into lowercase
ucase converts lowercase letters into uppercase
ASCII converts the file by translating the character set from
EBCDIC to ASCII
EBCDIC converts the file by translating the character set from
ASCII to EBCDIC
umask
For changing default permissions. When we create directories they have default
permissions 755 (rwxr-xr-x) and the files have default permission 644(rw-r- -r--).
[root@jmit ~]# umask
0022
Current umask is displayed. Subtracting 777-022=755 default permissions.
[root@jmit ~]# umask 077
For setting permission 077 i.e 700(rwx for owner and no permission group and others)
This umask is set only for the current session and also umask cannot change the
permission for existing files and directories. Normal user has different umask from root.
This umask is for directories. For files the default permission is 644 and maximum
permission can be set is 666 for normal and text file's.
Thus 666-022=644 is default setting. When we set umask as 077 the directories has 700
permissions and files have 600 permissions.
Example: How to store umask permanently
Every user has a .bashrc file. The startup file or logon scripts are written in this file. This
file is the first file to be read. To make umask permanent append this file with umask
<permission>. For example umask 077.
# vi is vim
alias vi='vim'
Ignoring an alias
To ignore aliases called ls and run ls command, enter:
\ls
OR
"ls"
Or just use the full path:
/bin/ls
• Provides visual interface to two directories at a time, and directory browsing with
mouse clicks
• Allows menu-driven file operations with dialogs and mouse or keyboard support
Has an open command line to your shell
• Runs commands through mouse clicks
• Extensive, built-in hypertext help screens
• Emulates and supports the ls, cp, ln, mv, mkdir, rmdir, rm, cd, pwd, find, chown,
chgrp, and tree commands
The Midnight Commander visual shell displays a graphical interface to Linux file
commands.
• Compares directory contents
• Uses customized menus so you can build your own commands
• Can use network links for telnet or FTP operations (see Hour 13, "Internet
Downloading and Browsing")
• Offers mouse-click decompression of files (see gzip)
• Can undelete files (if your Linux filesystem is configured to support this)
Midnight Commander is a handy and convenient tool to use for file handling and
directory navigation. You will have to invest some time in learning how to use this
program, but if you've used similar file-management interfaces, you'll feel right at home.
wall(write to all)
This command is used by administrator to send message to all currently logged user.
Syntax:
[root@localhost ~]#wall
<message to be send>
^d
Example:
[root@localhost ~]#wall
Save your data
No power backup
^d
write
This online communication commands lets you to write messages on another users
terminal.
Syntax:
[root@localhost ~]# Write <reception in name>
<messages>
^d
Example:
[root@localhost ~]# write Pooja
Hello Pooja sharma
what are you doing?
^d
On the execution of this command, the specified message is displayed on the terminal of
the user Pooja. If the recipient does not want to allow these message (sent by others
users) on this terminal then he can use message command .If he want to revoke this
option and want to allow any one to communicate with him then he can use message
command.
General format is Message (y/n)
Y Allows write access to your terminal.
N Disallows writes access to your terminal.
The messages without argument give the states of the messages setting.
The finger command can be used to know the user who are sent currently logged on the
system and to know which terminal of the users are set to messages and which are sent to
messages n. A* symbol is placed on those terminals where the messages set to n.
mail
This command offers off line communication.
Syntax: To sent mail,
[root@localhost ~]# mail (users name)
<Message>
cntl+d
The mail programmed mails the messages to the specified users. If the users (recipient)is
logged on the system , the messages you have new mail is display on the recipient
terminal .However the users is logged on the system or not ,the mail will be kept in the
mail box until the users issues the necessary command to read the mail. To check mails,
give the mail command with out arrangement. This command will list all the incoming
mails received since the latest usage of the mail command .A & symbol is displayed at
the bottom. This is called mail prompt. Here we can issue several mail prompt command
some command communication commands are given below.
Mail Prompt Commands Function
+ Display the next mail messages if exists.
_ Display the previous mail messages if exists
<Number> Display the specified number mail if exists
D Delete currently viewed mail
d<number> Delete the specified mail number if exists
s <filename> Store the current mail in specified file.
s <number><filename> Store the specified mail number in specified file.
R reply to current mail
r <number> reply to specified mail number
q Quit
bg
Put a process in the background. Linux provides the facility for background processes.
That is, when one processes is running in the foreground, another process can be
executed in the background .The ampersand symbol placed at the end of a command for
back ground processing.
fg
Put a process in the foreground.
Example:
[root@localhost ~]#fg sortemp.doc&
[3] 7610
jobs
An alternate way of listing your own processes.
[root@localhost]# sort emp.doc &
[1] 6465
In this case, the prompt returned because the process was put in the background.
[root@localhost]# bg
[1]+ emp.doc &
Now that we have a process in the background, it would be helpful to display a list of the
processes we have launched. To do this, we can use either the jobs command or the more
powerful ps command.
[root@localhost]# jobs
[1]+ Running emp.doc &
[root@localhost ~]# ps
PID TTY TIME CMD
6464 pts/2 00:00:00 bash
6465 pts/2 00:00:00 emp.doc
6466 pts/2 00:00:00 ps
kill
If you can want a command to terminate prematurely, process (ctrl +c) .This type of
interrupt characterless does not affect the background processes, because the background
processes are protected by the shell from these interrupt signals. This kill command is
used to terminate a background processes.
Syntax:
[root@localhost ~]# kill (-signal number) < PID.>
The PID is the processes identification number is the processes that we want to terminate
Use ps command to know the PID of the current processes. By default this kill command
uses the signal number 15 to terminate a process. But some programmed like login shell
simply ignore this signal of introduction, and continuous execution normally. In this case,
you can use the signal number 9 (often referred as sure kill.)
[root@localhost ~]# kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL
5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE
9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 17) SIGCHLD
18) SIGCONT 19) SIGSTOP 20) SIGTSTP 21) SIGTTIN
22) SIGTTOU 23) SIGURG 24) SIGXCPU 25) SIGXFSZ
26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGIO
30) SIGPWR 31) SIGSYS 34) SIGRTMIN 35) SIGRTMIN+1
36) SIGRTMIN+2 37) SIGRTMIN+3 38) SIGRTMIN+4 39) SIGRTMIN+5
40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8 43) SIGRTMIN+9
44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13
48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13
52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9
56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6 59) SIGRTMAX-5
60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2 63) SIGRTMAX-1
64) SIGRTMAX
will give you a list of the signals it supports. Most are rather obscure, but several are
useful to know:
Hang up signal. Programs can listen for this signal and act (or not
1 SIGHUP
act) upon it.
Now let's suppose that you have a program that is hopelessly hung (Netscape, maybe)
and you want to get rid of it. Here's what you do:
1. Use the ps command to get the process id (PID) of the process you want to
terminate.
2. Issue a kill command for that PID.
3. If the process refuses to terminate (i.e., it is ignoring the signal), send increasingly
harsh signals until it does terminate.
Example:
[root@localhost ~]# kill1209
This command terminate the processes who has the PID 1200
[root@localhost ~]# kill -9 1300
[root@localhost ~]# kill -9 0
This command kills all the processes including the logion shell. (The kernel it self being
the first processes gets the PID. The above command kills the kernel, so all the processes
are killed)
[root@localhost ~]# kill %1
This command kills first background process .
nohup
If a user wants processes that he has executed not to die even when he logged-out from
the system, you can use this nohup (no hang-up) command .Note that normally all the
process of a user are terminate if he has logs out.
Syntax:
[root@localhost ~]# nohup <commands >
Example:
[root@localhost ~]# nohup dataemp.doc&
434
Here, 434 is the PID of the process. Then the comment sort dataemp.doc will be executed
even if you logged out from the system. The out put of this command will be stored in a
file named nohup out.
at
This command is used to execute the specified Linux command at future time,
Syntax:
[root@localhost ~]# at time
<Commands>.
^d
(Press (ctrl+ d) at the end)
Here <time> specifies the time at which the specified command are to be executed.
Example:
[root@localhost ~]# at 12:00
echo “Lunch break”
^d
At offers the keywords –now , noon ,midnight, today and tomorrow and they convey
special meanings.
[root@localhost ~]# at noon
echo “lunch break’
^d
At also offers the keywords hours, days, weeks ,month ,and years, can be used with
+operator as shown in the following examples.
[root@localhost ~]# at 12:00+1 day at 122:00 tomorrow
[root@localhost ~]# at 13:00 Jan 20 , 2003+2 days --at 1 pm january20,2004
atq
This command is used to list the job submitted by you on at queue. This command lists
the job number. Scheduled date of execution.
Syntax: [root@localhost ~]# atq
atrm
This command is used to remove a job from at queue.
Syntax: atrm job number
Example
[root@localhost ~]# atq
2002-12-16-12:00 a teji
2002-12-17-12:0 a teji
2003-01-22 13:00 a teji
[root@localhost ~]# atrm 8
[root@localhost ~]# atq
2002-12-16-12:00 a abc
2003-01-22-13:00 a emp.doc
batch
This command is used to execute the specified command when the system load permitted
(when becomes nearly free).
Syntax:
[root@localhost ~]# batch
<commands>
^d
Any job schedule with batch also goes to the at queue, you can list or delete them through
atq and atrm respectively.
Example:
[root@localhost ~]# batch
Sort a. c
Sort b.c.
^d
pstree
This command is also used the check the process on the server. " pstree " command will
list all the running process in the form of a tree structure.
Example:
[root@localhost ~]# pstree
init─┬─agetty
├─antirelayd
├─bdflush
├─chkservd
├─4*[courierlogger───couriertcpd]
├─courierlogger───authdaemond───5*[authdaemond───authProg]
├─cpanellogd
├─cpdavd
├─cphulkd.pl
├─cpsrvd-ssl───cpsrvd-ssl
├─crond
├─entropychat
├─exim───exim─┬─3*[exim]
│ └─spamc
├─2*[exim]
├─exim───20*[exim]
├─eximstats
├─hpt_wt
├─httpd───56*[httpd]
├─interchange
├─keventd
├─7*[kjournald]
├─klogd
├─ksoftirqd_CPU0
├─ksoftirqd_CPU1
├─ksoftirqd_CPU2
├─ksoftirqd_CPU3
├─kswapd
├─kupdated
├─mailmanctl───8*[python2.4]
├─mdrecoveryd
├─6*[mingetty]
├─mysqld_safe───mysqld───mysqld───26*[mysqld]
├─named───named───6*[named]
├─portsentry
├─pure-authd
├─pure-ftpd
├─10*[python2.4]
├─scsi_eh_0
├─spamd───2*[spamd]
├─ssh
├─sshd─┬─sshd───sshd───bash───su───bash
│ └─sshd───sshd───bash───su───bash───pstree
├─syslogd
└─xinetd
w
This command is also find the load and users on the server. "w" command will provide a
brief description about the load, time, number of users and the uptime of the server.
Example:
[root@localhost ~]# w
15:23:31 up 6:25, 3 users, load average: 0.01, 0.01, 0.00
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
root :0 09:12 ?xdm? 4:25 1.03s /usr/bin/gnome-
root pts/1 :0.0 12:28 2:54m 0.01s 0.01s bash
root pts/2 :0.0 15:23 0.00s 0.01s 0.00s w
uptime
This command gives the basic information about the uptime and load of the server.
Example:
[root@localhost ~]# uptime
15:23:39 up 6:25, 3 users, load average: 0.01, 0.01, 0.00
top
This command is used to find the load on the server. “top " command can also be used to
find the process and users that causes load on the server. It gives information about the
total process, sleeping process, the zombie process etc.
Example:
[root@localhost ~]# top
top - 15:24:48 up 6:26, 3 users, load average: 0.16, 0.03, 0.01
Tasks: 113 total, 1 running, 112 sleeping, 0 stopped, 0 zombie
Cpu(s): 0.7% us, 0.3% sy, 0.0% ni, 99.0% id, 0.0% wa, 0.0% hi, 0.0% si
Mem: 497840k total, 418308k used, 79532k free, 14036k buffers
Swap: 1052216k total, 128k used, 1052088k free, 145996k cached
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
4488 root 15 0 179m 45m 6240 S 1 9.3 2:16.72 X
6896 root 15 0 37336 13m 8608 S 0 2.8 0:01.65 gnome-terminal
1 root 16 0 2996 552 472 S 0 0.1 0:00.52 init
2 root RT 0 0 0 0 S 0 0.0 0:00.00 migration/0
3 root 34 19 0 0 0 S 0 0.0 0:00.81 ksoftirqd/0
4 root RT 0 0 0 0 S 0 0.0 0:00.00 migration/1
5 root 34 19 0 0 0 S 0 0.0 0:00.84 ksoftirqd/1
6 root 5 -10 0 0 0 S 0 0.0 0:00.03 events/0
7 root 5 -10 0 0 0 S 0 0.0 0:00.03 events/1
8 root 14 -10 0 0 0 S 0 0.0 0:00.01 khelper
9 root 15 -10 0 0 0 S 0 0.0 0:00.00 kacpid
28 root 5 -10 0 0 0 S 0 0.0 0:00.00 kblockd/0
From the above example you can see the load average, total processes, sleeping processes
and the CPU usage. You can find the load average (here the load average is “4.95 " ), the
memory usage, stats, swap and the list of process and its users.
netconfig
CUI based.
Used to configure network interface.
Used by text based installation methods.
redhat-config-network
This is a GUI administration tool that allows you to configure several aspects of your
networking: interfaces, boot protocols, host resolution, routing, and more.
ifup / ifdown
These shell script wrappers allow you to bring an interface up and take it down. They use
the configuration information in the /etc/sysconfig directory to configure the interface
specified.
For example, to bring up interface eth0, simply type:
[root@localhost ~]# ifup eth0
ping
ping is used to check network connectivity. Ping sends dummy packets to host to check
weather host is responding or not. If host working then it sends reply packets to client and
it continue sly send reply packets. To stop it Press Ctrl+c .It uses ICMP echo request and
echo reply to test the connectivity. Host may not be responding due to following reasons:
The remote host is down.
Some point in the network in-between the two hosts is down.
A device in-between the two hosts is filtering ICMP packets.
Examples:
[root@localhost ~]# ping 192.168.100.256
[root@localhost ~]# ping -b 192.168.100.256
ping options:
traceroute
traceroute is also used to test network connectivity. However, it displays each hop along
the way from the source to the destination. It can help you determine if the problem is
with the remote host itself, or some point in-between the hosts.
Example:
[root@localhost ~]# traceroute 192.168.100.256
This will print a line for each hop in-between the local and remote host
(192.168.100.256) as well as a line for the final destination up to a maximum of 30 hops.
ifconfig
The ifconfig command configures a network interface, or displays its status if no options
are provided. If no arguments are provided, the current state of all interfaces is displayed.
Syntax: [root@localhost ~]# ifconfig interface options address
Where interface specifies the name of the network interface (e.g. eth0 or eth1).
To get the IP address of the host machine we enter at the command prompt the
command
[root@localhost ~]# ifconfig
This provides us with the network configuration for the host machine. For example
Ethernet adapter
IP address 152.106.50.60
Subnet Mask 255.255.255.0
Default Gateway 152.106.50.240
Example:
[root@localhost ~]# ifconfig eth0 192.168.1.10 netmask 255.255.255.0 up
This configures interface eth0 with an IP of 192.168.1.10/255.255.255.0. Note that "up"
is assumed if left off. A default network mask will also be determined by the IP if it is not
specified.
arp
arp is used to administer the arp cache. It can view, add, and delete entries in the
cache.
View arp cache:
[root@localhost ~]# arp
This will display something like:
Address HWtype HWaddress Flags Mask Iface
192.168.100.256 ether 00:60:08:27:CE:A2 C eth0
192.168.100.169 ether 00:60:08:27:CE:B2 CM eth0
The "C" flag means it's a complete entry. The "M" flag indicates it's an entry added
manually and it is permanent.
Add an entry:
[root@localhost ~]# arp -s 192.168.100.145 00:60:08:27:CE:B2
Delete an entry:
[root@localhost ~]# arp -d 192.168.100.256
netstat
netstat provides a lot of useful information, including: Routing tables, Interface statistics
(dropped packets, buffer overruns, etc.) ,Network connections ,Multicast memberships.
Examples:
[root@localhost ~]# netstat -i
Display interface statistics.
[root@localhost ~]# netstat -lpe
Display all listening sockets and the programs that own them
[root@localhost ~]# netstat -r
Display routing information
[root@localhost ~]# netstat -ape
Show all listening and non-listening sockets
nslookup
The nslookup command queries a DNS nameserver. It can be run in interactive
mode. If no host name is provided, then the program enters interactive mode. By
default, the DNS server specified in
/etc/resolv.conf
is used unless another is specified. If we want to specify a server but not look up a
Specified host, we must provide a - in place of the host. The syntax is
[root@localhost ~]# nslookup [host|-[server]]
hostname
The hostname command displays or sets the system’s host name. If no flags or arguments
are given, then the host name of the system is displayed.
Syntax:-
[root@localhost ~]# hostname [-a] [--alias] [-d]
[--domain] [-f] [--fqdn] [-i]
[--ip-address] [--long] [-s]
[--short] [-y] [--yp] [--nis]
Imporloginrtant
-a/--alias: Displays the alias name of host if available.
-d/--domain: Displays the DNS domain name of the host.
f/--fqdn/--long: Displays the fully qualified domain name of the host.
i/--ip-address: Displays the IP address of the host.
s/--short: Displays the host name without the domain name.
y/--yp/--nis: Displays the NIS domain name of the system.
rcp
rcp copies files between machines. Each file or directory argument is either a remote file
name of the form ``rname@rhost:path'', or a local file name .
Syntax:
rcp [-px ] file1 file2
rcp [-px ] [-r ] file ... directory
-r If any of the source files are directories, rcp copies each subtree rooted at that
name; in this case the destination must be a directory.
-p The -p option causes rcp to attempt to preserve (duplicate) in its copies the
modification times and modes of the source files.
If path is not a full path name, it is interpreted relative to the login directory of the
specified user ruser on rhost or your current user name if no other remote user name is
specified. A path on a remote host may be quoted (using \, ", or ´) so that the
metacharacters are interpreted remotely.
rcp does not prompt for passwords; it performs remote execution via rsh, and requires the
same authorization.
rcp handles third party copies, where neither source nor target files are on the current
machine.
EXAMPLES
The command rcp copies files between computer systems. To be able to use the rcp
command, both computers need a ".rhosts" file in the user's home directory, which would
contain the names of all the computers that are allowed to access this computer along
with the user name. Here is an example of an .rhosts file:
jmit.ac.in jmit
cse.ac.in jmitcse
[root@localhost ~]#rcp teji.txt jmit.ac.in:teji.doc
Copies teji.txt from the local machine to the user's home directory on the computer with URL jmit.ac.in,
assuming that the user names are the same on both systems.
[root@localhost ~]#rcp teji.txt pooja@:jmit.ac.in:pooja.doc
Copies teji.txt from the local machine to the home directory of user pooja on the
computer with URL jmit.ac.in.
Shell metacharacters which are not quoted are interpreted on local machine, while quoted
metacharacters are interpreted on the remote machine. For example, the command
[root@localhost ~]#rsh otherhost cat remotefile >> localfile
Appends the remote file remotefile to the local file localfile while
[root@localhost ~]#rsh otherhost cat remotefile ">>" other_remotefile
Appends remotefile to other_remotefile
rsync
rsync is a program that behaves in much the same way that rcp does, but has many more
options and uses the rsync remote-update protocol to greatly speed up file transfers when
the destination file already exists.
The rsync remote-update protocol allows rsync to transfer just the differences between
two sets of files across the network link, using an efficient checksum-search algorithm
described in the technical report that accompanies this package.
Some of the additional features of rsync are:
1) Support for copying links, devices, owners, groups and permissions
2) Exclude and exclude-from options similar to GNU tar
3) A CVS exclude mode for ignoring the same files that CVS would ignore
4) Can use any transparent remote shell, including rsh or ssh
5) Does not require root privileges
6) Pipelining of file transfers to minimize latency costs
7) Support for anonymous or authenticated rsync servers (ideal for mirroring)
There are six different ways of using rsync. They are:
1) For copying local files. This is invoked when neither source nor destination path
contains a : separator
2) For copying from the local machine to a remote machine using a remote shell
program as the transport (such as rsh or ssh). This is invoked when the destination
path contains a single: separator.
3) For copying from a remote machine to the local machine using a remote shell
program. This is invoked when the source contains a : separator.
4) For copying from a remote rsync server to the local machine. This is invoked
when the source path contains a :: separator or a rsync:// URL.
5) For copying from the local machine to a remote rsync server. This is invoked
when the destination path contains a :: separator.
6) For listing files on a remote machine. This is done the same way as rsync transfers
except that you leave off the local destination.
Note that in all cases (other than listing) at least one of the source and destination paths
must be local.
Examples:
You use rsync in the same way you use rcp. You must specify a source and a destination,
one of which may be remote.
Perhaps the best way to explain the syntax is some examples:
[root@localhost ~]#rsync *.c foo:src/
This would transfer all files matching the pattern *.c from the current directory to the
directory src on the machine foo. If any of the files already exist on the remote system
then the rsync remote-update protocol is used to update the file by sending only the
differences. See the tech report for details.
[root@localhost ~]#rsync -avz foo:src/bar /data/tmp
this would recursively transfer all files from the directory src/bar on the machine foo into
the /data/tmp/bar directory on the local machine. The files are transferred in "archive"
mode, which ensures that symbolic links, devices, attributes, permissions, ownerships etc
are preserved in the transfer. Additionally, compression will be used to reduce the size of
data portions of the transfer.
[root@localhost ~]#rsync -avz foo:src/bar/ /data/tmp
a trailing slash on the source changes this behavior to transfer all files from the directory
src/bar on the machine foo into the /data/tmp/. A trailing / on a source name means "copy
the contents of this directory". Without a trailing slash it means "copy the directory". This
difference becomes particularly important when using the --delete option.
You can also use rsync in local-only mode, where both the source and destination don't
have a ':' in the name. In this case it behaves like an improved copy command.
[root@localhost ~]#rsync somehost.mydomain.com::
this would list all the anonymous rsync modules available on the host
somehost.mydomain.com.
TFTP
Terminal file transfer program .The utility allows a user to transfer files to and from a
remote network site.
Check that TFTP server package is installed by running following command
Run service
[root@localhost ~]#/etc/init.d/xinetd restart
EXAMPLES:
ftp>help
This lists the commands that you can use to show the directory contents, transfer files,
and delete files.
ftp> ls
This command prints the names of the files and sub-directories in the current directory on
the remote computer.
ftp>cd teji
This command changes the current directory to the subdirectory "teji", if it exists.
ftp>cd ..
Changes the current directory to the parent directory.
ftp>ascii
Changes to "ascii" mode for transferring text files.
ftp>binary
Changes to "binary" mode for transferring all files that are not text files.
ftp>get teji.txt
Downloads the file teji.txt from the remote computer to the local computer. Warning: If
there already is file with the same name it will be overwritten.
ftp>put seema.txt
Uploads the file seema.txt from the local computer to the remote computer. Warning: If
there already is file with the same name it will be overwritten.
ftp> !ls
A '!' in front will execute the specified command on the local computer. So '!ls' lists the
file names and directory names of the current directory on the local computer.
ftp> mget *.txt
With mget you can download multiple text files. This command downloads all files that
end with ".txt".
ftp>mput *.sh
ftp >bye
Exits the ftp program.
telnet
The telnet command is used to communicate with another host using the TELNET
protocol. If telnet is invoked without the host argument, it enters command mode,
indicated by its prompt (telnet> ) In this mode, it accepts and executes the commands . If
it is invoked with arguments, it performs an open command with those arguments.
Installation and configuration:
Check that telnet server package is installed by running following command
[root@localhost ~]# rpm –qa telnet –server*
if not then install it you can find packages at Url:-http//rpmfind.net and in search bar
enter telnet –server and select according to your OS as red hat or fedora or some other .
Run service
[root@localhost ~]# /etc/init.d/xinetd restart
But you can login as user and not able to logon as root in telnet to enable
Root as root has super user privileges so change entry in
Simply edit the file /etc/securetty and add the following to the end of the File.
3.1 vi editor
vi stands for ”Visual Editor”. vi is popular because it is small and is found on virtually all
Unix systems. To start the vi editor, we type its name at the shell prompt (command line).
[root@localhost]# vi
If we know the name of the file we want to create or edit, we can issue the vi
Command with the file name as an argument. For example, to create the file
myshell.doc with vi,
we enter
[root@localhost]# vi myshell.doc
To edit a given file for example myshell.doc we enter
[root@localhost]# vi myshell.doc
When vi becomes active, the terminal screen clears and a tilde character ~ appears on the
left side of very screen line, except for the first. The ~ is the empty-buffer line flag. The
cursor is at the leftmost position of the first line. We probably see 20 to 22 of the tilde
characters at the left of the screen. If that’s not the case, check the value of TERM. When
we see this display we have successfully started vi. Then vi is in command mode, waiting
for our first command.
vi’s Operation Modes
Command mode: In command mode, vi interprets our keystrokes as commands. We
press any character from the keyboard to perform an action related to it.
Insert mode: We use input mode only for entering text. Most word processors start in
input mode, but vi does not. We must go into input mode by pressing a or i before we
start entering text
Save mode: After this there is need to save the changes made in the file. Then explicitly
press <Esc> to return to command mode. There is also a command line mode. This mode
is used for complex commands such as searching and to save our file or to exit vi. We
enter this mode by typing “:”, “/”, “?” or “!”. A few of these commands are:
:w – write to file
:wq - write to file and exit vi
:q! – Forcefully quit without saving file.
:q Exits after making no changes to the buffer or exits after the buffer is modified and
saved to a file
:q! Exits and abandons all changes to the buffer since it was last saved to a file
:wq! Writes buffer to the working read only file and then exits
:x Perform same operation as :wq
ZZ Perform same operation :wq
Working with vi editor
1. Start vi
Type vi and press Enter.
2. Go to input mode.
Press I or insert key
3. Enter the text.
Type the text into the buffer.
4. Press Esc.
5. Type: wq <filename >for write and quit.
Control Commands
There are following useful command which you can use along with Control Key.
Command Description
CTRL+d Move forward 1/2 screen
CTRL+d Move forward 1/2 screen
CTRL+f Move forward one full screen
CTRL+u Move backward 1/2 screen
CTRL+b Move backward one full screen
CTRL+e Moves screen up one line
CTRL+y Moves screen down one line
CTRL+u Moves screen up 1/2 page
CTRL+d Moves screen down 1/2 page
CTRL+b Moves screen up one page
CTRL+f Moves screen down one page
CTRL+I Redraws screen
Editing Files
To edit the file, you need to be in the insert mode. There are many ways to enter insert
mode from the command mode:
Command Description
i Inserts text before current cursor location.
I Inserts text at beginning of current line.
A Inserts text after current cursor location.
A! Inserts text at end of current line.
O Creates a new line for text entry below cursor location.
Deleting Characters
Here is the list of important commands which can be used to delete characters and lines
in an opened file.
Command Description
X Deletes the character under the cursor location.
X Deletes the character before the cursor location.
Dw Deletes from the current cursor location to the next word.
D^ Deletes from current cursor position to the beginning of the line.
D$ Deletes from current cursor position to the end of the line.
D Deletes from the cursor position to the end of the current line.
Dd Deletes the line the cursor is on.
As mentioned above, most commands in vi can be prefaced by the number of times you
want the action to occur. For example, 2x deletes two character under the cursor location
and 2dd deletes two lines the cursor is on.
Change Commands
You also have the capability to change characters, words, or lines in vi without deleting
them. Here are the relevant commands.
Command Description
Cc Removes contents of the line, leaving you in insert mode.
Changes the word the cursor is on from the cursor to the lowercase
Cw
w end of the word.
Replaces the character under the cursor. vi returns to command
R
mode after the replacement is entered.
Overwrites multiple characters beginning with the character
R currently under the cursor. You must use Esc to stop the
overwriting.
Replaces the current character with the character you type.
S
Afterward, you are left in insert mode.
Deletes the line the cursor is on and replaces with new text. After
S
the new text is entered, vi remains in insert mode.
Set Commands
You can change the look and feel of your vi screen using the following: set commands.
To use these commands you have to come in command mode then type: set followed by
any of the following options:
Command Description
:set ic Ignores case when searching
:set ai Sets auto indent
:set noai To unset auto indent
:set nu Displays lines with line numbers on the left side.
Sets the width of a software tabstop. For example you would set a
:set sw
shift width of 4 with this command: :set sw=4
If wrapscan is set, if the word is not found at the bottom of the
:set ws
file, it will try to search for it at the beginning.
If this option has a value greater than zero, the editor will
:set wm automatically "word wrap". For example, to set the wrap margin to
two characters, you would type this: :set wm=2
:set ro Changes file type to "read only"
:set term Prints terminal type
:set bf Discards control characters from input
Running Commands
The vi has the capability to run commands from within the editor. To run a command,
you only need to go into command mode and type:! Command.
For example, if you want to check whether a file exists before you try to save your file to
that filename, you can type :! ls and you will see the output of ls on the screen.
When you press any key (or the command's escape sequence), you are returned to your vi
session.
Replacing Text
The substitution command (:s/) enables you to quickly replace words or groups of words
within your files. Here is the simple syntax:
:s/search/replace/g
The g stands for globally. The result of this command is that all occurrences on the
cursor's line are changed.
Major Modes
These include modes for various programming languages (e.g. Bash, C, Lisp, and Perl),
for text processing (e.g. Latex, SGML, troff, and plain text), and even Dired (Directory
Editor) for managing directories.
Minor Modes
These allow you to set or unset features that are independent of the major mode, e.g.
auto-fill (word wrapping), insert vs overwrite, and auto-save.
If you spend a lot of time editing files with a particular structure, then a customised
version of emacs will pay real dividends by reducing the number of keystrokes needed to
complete a specific task.
Working with emacs editor
1. Start emacs.
Type emacs and press <Enter>.
2. Enter the text.
Type the text into the buffer.
3. Save buffer to file.
Press Ctrl-c Ctrl-s and answer y to the prompt asking to save the file; then press
Enter.
4. Name the file.
Type the file name and press <Enter>.
5. Quit emacs.
Press Ctrl-x Ctrl-c.
To start editing a new or existing file using emacs, simply type the following on
command prompt.
[root@localhost ~]# emacs filename
Where filename is the file to be edited.
Two important key sequences which are used to start many command sequences are
Cntl+x (holding down the “ctrl” key while typing “x”)
[esc]-x (simply pressing the “esc” key followed by typing “x”)
To save the file being edited the sequence is ^x^s.
To exit (and be prompted to save) emacs, the sequence is ^x^c.
To open another file within emacs, the sequence is ^x^f. This sequence can be used to
open an existing file as well as a new file. If you have multiple files open, emacs stores
them in different “buffers”.
To switch from one buffer to another use the key sequence ^x-b. The arrow keys usually
work as the cursor movement keys, but there are other nagivation keys Combinations
listed below.
Running emacs
[root@localhost ~]# emacs <filename>
Run emacs .Adding a '&' after the above command will run emacs in the background,
freeing up your shell)
^z Suspend emacs
^x^c Quit emacs
^x^f Load a new file into emacs
^x^v Load a new file into emacs and unload previous file
^x^s Save the file
^x-k Kill a buffer
Moving About
^f Move forward one character
^b Move backward one character
^n Move to next line
^p Move to previous line
^a Move to beginning of line
^e Move to end of line
^v Scroll down a page
[ESC]-v Scroll up a page
[ESC]-< Move to beginning of document
^x-[Move to beginning of page
[ESC]-> Move to end of document
^x-] Move to end of page
^l Redraw screen centered at line under the cursor
^x-o Move to other screen
^x-b Switch to another buffer
Searching
^s Search for a string
^r Search for a string backwards from the cursor (quit both of these with ^f)
[ESC]-% Search-and-replace
Deleting
^d Deletes letter under the cursor
^k Kill from the cursor all the way to the end of the line
^y Yanks back all the last kills.
^k ^y combination you can get a primitive cut-paste effect to move text around
Regions
emacs defines a region as the space between the mark and the point. A mark is set with
^-space (control-spacebar). The point is at the cursor position.
[ESC]-w Copy the region
^w Delete the region. Using ^y will also yank back the last region
killed or copied — this is the way to get a cut/copy/paste effect with
regions.
Screen Splitting
^x-2 Split screen horizontally
^x-3 Split screen vertically
^x-1 Make active window the only screen
^x-0 Make other window the only screen
Miscellaneous
[ESC]-$ Check spelling of word at the cursor
^g In most contexts, cancel, stop, go back to normal command
[ESC]-x goto-line num Goes to the given line number
^x-u Undo
[ESC]-x shell Start a shell within emacs
[ESC]-q Re-flow the current line-breaks to make a single paragraph of text
15
Compiling
[ESC]-x compile Compile code in active window. Easiest if you have a makefile set
up.
^c ^c Do this with the cursor in the compile window, scrolls to the next
compiler error. Cool!
Getting Help
^h emacs help
^h t Run the emacs tutorial
emacs does command completion for you. Typing [ESC]-x space will give you a list of
emacs
commands. There is also a man page on emacs. Type man emacs in a shell.
Printing Your Source Files
There's a really neat way to print out hardcopies of your source files. Use a command
called “enscript”. Commonly, it's used at the Unix command line as follows:
enscript -2GrPsweet5 binky.c lassie.c *.h
This example shoes printing the two source files binky.c and lassie.c, as well as
all of the header files to printer sweet5. You can change these parameters to fit your
needs
Features include:
• 3 modes:
o Command mode
o Insert mode
o Command line mode
• Unlimited undo
• Multiple windows and buffers
• Flexible insert mode
• Syntax highlighting - highlight portions of the buffer in different colors or styles,
based on the type of file being edited
• Interactive commands
o Marking a line
o vi line buffers
o Shift a block of code
• Block operators
• Command line history
• Extended regular expressions
• Edit compressed/archive files (gzip, bzip2, zip, tar)
• Filename completion
• Block operations
• Jump tags
• Folding text
• Indenting
• ctags and cscope intergration
• 100% vi compatibility mode
• Plugins to add/extend functionality
• Macros
• vimscript, Vim's internal scripting language
• Unicode support
• Multi-language support
• Integrated On-line help
Features include:
• Powerful syntax highlighting and bracket matching
• MDI, window splitting, window tabbing
• Spell checking
• CR, CRLF, LF newline support
• Encoding support (utf-8, utf-16, ascii etc.)
• Encoding conversion
• Search and replace text using regular expressions
• Drag and drop text editing
• Code and text folding
• Infinite undo/redo support
• Block selection mode
• Auto indentation
• Auto completion support
• Integrated shell
• Wide protocol support (http, ftp, ssh, webdav etc.)
• Plugin architecture for the application and editor component
• Customizable shortcuts
• Integrated command line
• Full DCOP scripting
• Scriptable using JavaScript .
•
A regular expression is a set of characters that specify a pattern. Regular expressions are
used when you want to search for specify lines of text containing a particular pattern.
Most of the UNIX utilities operate on ASCII files a line at a time. Regular expressions
search for patterns on a single line, and not for patterns that start on one line and end on
another. It is simple to search for a specific word or string of characters. Almost every
editor on every computer system can do this. Regular expressions are more powerful and
flexible. You can search for words of a certain size. You can search for a word with four
or more vowels that end with an "s". Numbers, punctuation characters, you name it, a
regular expression can find it. What happens once the programs you are using find it is
another matter? Some just search for the pattern. Others print out the line containing the
pattern. Editors can replace the string with a new pattern. It all depends on the utility.
^ And $
Most UNIX text facilities are line oriented. Searching for patterns that span several lines
is not easy to do. You see, the end of line character is not included in the block of text
that is searched. It is a separator. Regular expressions examine the text between the
separators. If you want to search for a pattern that is at one end or the other, you use
anchors. The character "^" is the starting anchor, and the character "$" is the end anchor.
The regular expression "^A" will match all lines that start with a capital A. The
expression "A$" will match all lines that end with the capital A. If the anchor characters
are not used at the proper end of the pattern, then they no longer act as anchors. That is,
the "^" is only an anchor if it is the first character in a regular expression. The "$" is only
an anchor if it is the last character. The expression "$1" does not have an anchor. Neither
is "1^". If you need to match a "^" at the beginning of the line, or a "$" at the end of a
line, you must escape the special characters with a backslash. Here is a summary:
Pattern Matches
^B "B" at the beginning of a line
B$ "B" at the end of a line
B^ "B^" anywhere on a line
$B "$B" anywhere on a line
^^ "^" at the beginning of a line
$$ "$" at the end of a line
Example:
[root@localhost~]#cat>name.txt
ram
mohan
sohan
seema
akshara
Cntl+d
[root@localhost ~]# sort name.txt > sortfile
[root@localhost~]#cat sortfile
Sorted output will be stored in sortfile
Example:
[root@localhost ~]# cat >jmitstaff.doc
reena
Pooja sharma
Vipul gupta
Krishan sharma
Shilpa mehta
Cntl +d
[root@localhost ~]# cat >> name.txt jmitstaff.doc
[root@localhost ~]#cat jmitstaff.doc
Example:
[root@localhost~]#tr "[a-z]" "[A-Z]" < name.txt > capsnames
[root@localhost~]# cat capsnames
tr command is used to translate all lower case characters to upper-case letters. It takes
input from name.txt file, and tr's output is redirected to capsnames file.
4.3 PIPES
A pipe is a way to connect the output of one program to the input of another program
without any temporary file.
Pipe:
"A pipe is nothing but a temporary storage place where the output of one command is
stored and then passed as the input for second command. Pipes are used to run more than
two commands (Multiple commands) from same command line."
Syntax:-command1 | command2
Examples:
[root@localhost~]# ls | more
Output of ls command is given as input to more command So that output is printed one
screen full page at a time.
[root@localhost~]# who | sort
Output of who command is given as input to sort command sorted list of users will be
printed on screen.
[root@localhost~]#ls -l | wc
Output of ls command is given as input to wc command. It will print number of lines,
words and characters of the files in current directory
[root@localhost~]# who | sort > loggedusers
Output of who command is given as input to sort command and result is stored in
loggedusers file
4.4 FILTERS
Filters take standard input and perform an operation upon it and send the results to
standard output. These filters are used to display the contents of a file in sorted order,
extract the lines of a specified file that contains a specific pattern. A filter performs some
kind of process on the input and gives output.
Sort
This command sorts the contents of a given file based on ASCII value of characters.
Syntax: sort [options] <Filename>
Various options available with Sort command are
• -m <filelist>
[root@localhost ~]# sort staff.doc -m staff.doc
1001 tajinder IT Information Technology 19-02-1979
1001 tajinder IT Information Technology 19-02-1979
1005 vipul CSE computer Engg. 4-10-1984
1005 vipul CSE computer Engg. 4-10-1984
1006 krishan COM commerce 6-10-1987
1004 vikas CSE computer Engg. 19-9-1982
1003 pooja IT Information Technology 23-9-1981
1002 reena IT Information Technology 6-5-1983
1006 krishan COM commerce 6-10-1987
1004 vikas CSE computer Engg. 19-9-1982
1003 pooja IT Information Technology 23-9-1981
1002 reena IT Information Technology 6-5-1983
In the above example, two already sorted files are merged with each other using -m
option.
• -o <Filename>
[root@localhost ~]# sort staff.doc -o staff.txt
[root@localhost ~]# cat staff.txt
1001 tajinder IT Information Technology 19-02-1979
1002 reena IT Information Technology 6-5-1983
1003 pooja IT Information Technology 23-9-1981
1004 vikas CSE computer Engg. 19-9-1982
1005 vipul CSE computer Engg. 4-10-1984
1006 krishan COM commerce 6-10-1987
• -r <Filename>
[root@localhost ~]# sort -r staff.doc
1006 krishan COM commerce 6-10-1987
1005 vipul CSE computer Engg. 4-10-1984
1004 vikas CSE computer Engg. 19-9-1982
1003 pooja IT Information Technology 23-9-1981
1002 reena IT Information Technology 6-5-1983
1001 tajinder IT Information Technology 19-02-1979
In the above example, the file is sorted in the reverse order by using the -r option.
• -n <filename>
[root@localhost ~]# sort -n staff.doc
1001 tajinder IT Information Technology 19-02-1979
1002 reena IT Information Technology 6-5-1983
1003 pooja IT Information Technology 23-9-1981
1004 vikas CSE computer Engg. 19-9-1982
1005 vipul CSE computer Engg. 4-10-1984
1006 krishan COM commerce 6-10-1987
In the above example, the sort with -n option will arrange its input according to numerical
value. As per rule, the digits, alphabets & special symbols are converted into their ASCII
value and then the sorting takes place, leading to uncertain results. Sort with -n option is
used to overcome this limitation.
• -c <Filename>
[root@localhost ~]# sort -c staff.doc
sort: staff.doc:4: disorder: 1004 vikas CSE computer Engg. 19-9-1982
[root@localhost ~]# cat staff.doc
1001 tajinder IT Information Technology 19-02-1979
1005 vipul CSE computer Engg. 4-10-1984
1006 krishan COM commerce 6-10-1987
1004 vikas CSE computer Engg. 19-9-1982
1003 pooja IT Information Technology 23-9-1981
1002 reena IT Information Technology 6-5-1983
In the above example, the -c option checks whether the given file is sorted or not.
If not, then it specifies the point of disorder.
• +pos <Filename>
[root@localhost ~]# sort +1 staff.doc
1006 krishan COM commerce 6-10-1987
1006 krishan IT Information Technology 6-10-1987
1003 pooja IT Information Technology 23-9-1981
1002 reena IT Information Technology 6-5-1983
1001 tajinder IT Information Technology 19-02-1979
1004 vikas CSE computer Engg. 19-9-1982
1005 vipul CSE computer Engg. 4-10-1984
In the above example, +1 specifies that the sort operation is being performed on the
second field i.e. sorting starts after the specified field number in the command parameter.
• -v option
[root@localhost ~]# grep -v "krishan" staff.doc
1001 tajinder IT Information Technology 19-02-1979
1005 vipul CSE computer Engg. 4-10-1984
1004 vikas CSE computer Engg. 19-9-1982
1003 pooja IT Information Technology 23-9-1981
1002 reena IT Information Technology 6-5-1983
In the above example, the only lines that do not match the specified pattern are displayed.
• -n option
[root@localhost ~]# grep -n "krishan" staff.doc
3:1006 krishan COM commerce 6-10-1987
In the above example, the resultant lines are displayed along with their line numbers.
• -c option
[root@localhost ~]# grep -c "IT" staff.doc
3
In above example, grep will search all occurrences of IT word and then -c option will
print the total number of occurrences of the specified word.
[root@localhost ~]# grep "IT" staff.doc
1001 tajinder IT Information Technology 19-02-1979
1003 pooja IT Information Technology 23-9-1981
1002 reena IT Information Technology 6-5-1983
• -<number> option
[root@localhost ~]# grep -1 "COM" staff.doc
1005 vipul CSE computer Engg. 4-10-1984
1006 krishan COM commerce 6-10-1987
1004 vikas CSE computer Engg. 19-9-1982
This example displays the lines matching with the specified pattern along with the
<number> of lines above and below.
• . symbol
[root@localhost ~]# grep "CO." staff.doc
1006 krishan COM commerce 6-10-1987
In this example, (.) symbol is used to match a single character.
• ^<character>
[root@localhost ~]# grep "^1" staff.doc
1001 tajinder IT Information Technology 19-02-1979
1005 vipul CSE computer Engg. 4-10-1984
1006 krishan COM commerce 6-10-1987
1004 vikas CSE computer Engg. 19-9-1982
1003 pooja IT Information Technology 23-9-1981
1002 reena IT Information Technology 6-5-1983
In this example, the lines beginning with “1” are matched and displayed.
• <character>$
[root@localhost ~]# grep "7$" staff.doc
1006 krishan COM commerce 6-10-1987
This example displays only those matched lines that are ending with the character
specified in the <character>.
It will display the lines ending with “7”.
egrep command
This command provides more features than simple grep command. It offers multiple
pattern matching. This is possible using pipe(|) symbol.
Example:
[root@localhost ~]# egrep "krishan|reena" staff.doc
1006 krishan COM commerce 6-10-1987
1002 reena IT Information Technology 6-5-1983
In this example, multiple patterns like krishan and reena are matched using egrep
command.
fgrep command
This command works just like grep with the only point of difference is the inability of
fgrep to work on regular expressions.
[root@localhost ~]# fgrep "krishan" staff.doc
1006 krishan COM commerce 6-10-1987
[root@localhost ~]# fgrep "kri*" staff.doc
This example shows that fgrep works fine for the simple grep operations but when the
use of regular expressions is inculcated, the fgrep command is no longer useful.
more
The more command is used to display the output page by page without scrolling up on
the screen fastly.
Keys: Space bar/[f] key to scroll one screen forward.
[b] key to scroll backward one screen backward.
[q] key to quit displaying.
Syntax: more<Filename>
Example: [root@localhost ~]# more staff.doc
pr
This command is used to display the file contents along with the suitable headers and
footers. The header part contains last modification date and time along with file name and
page number.
Syntax: pr [-options] <Filename>
Various available options are
• -n option: This is used to number the lines, display the header at the top and increase
the page size to the default value i.e. 66 lines.
[root@localhost ~]# pr -n staff.doc
2009-11-04 14:11 staff.doc Page 1
1 1001 tajinder IT Information Technology 19-02-1979
2 1005 vipul CSE computer Engg. 4-10-1984
3 1006 krishan COM commerce 6-10-1987
4 1004 vikas CSE computer Engg. 19-9-1982
5 1004 pooja IT Information Technology 23-9-1981
6 1002 reena IT Information Technology 6-5-1983
7 1001 tajinder IT Information Technology 19-02-1979
• -t option: This option turns off the heading at the top of the page.
[root@localhost ~]# pr -t staff.doc
1001 tajinder IT Information Technology 19-02-1979
1005 vipul CSE computer Engg. 4-10-1984
1006 krishan COM commerce 6-10-1987
1004 vikas CSE computer Engg. 19-9-1982
1004 pooja IT Information Technology 23-9-1981
1002 reena IT Information Technology 6-5-1983
1001 tajinder IT Information Technology 19-02-1979
cut
This command is used to cut the columns/fields of a specified file.
Syntax: cut [-options] <Filename>
Options available are
• -c <columns>
The column with the number given in the <columns> from the file being specified.
[root@localhost ~]# cut -c 4 staff.doc
1
5
6
4
4
2
1
In this example, the 4th column from the file staff.doc containing data is being displayed
on the screen.
We can also provide the range of the column numbers to be printed i.e 1-4.
[root@localhost ~]# cut -c 1-4 staff.doc
1001
1005
1006
1004
1004
1002
1001
• -f <fields>
This option is used to cut the fields with the number given in the <fields> from the file
being specified.
[root@localhost ~]# cut -f 1-2 staff.doc
1001 tajinder
1005 vipul
1006 krishan
1004 vikas
1004 pooja
1002 reena
paste
This command is used to concatenate the contents of the specified files into a single file
vertically.
Syntax: paste < filename1> <filename2>....
Examples:
[root@localhost ~]# cat staff.doc
1001 tajinder IT Information Technology 19-02-1979
1005 vipul CSE computer Engg. 4-10-1984
1006 krishan COM commerce 6-10-1987
[root@localhost ~]# cat staff.doc | tr -d "(a-c)"
1001 tjinder IT Informtion Tehnology 19-02-1979
1005 vipul CSE omputer Engg. 4-10-1984
1006 krishn COM ommere 6-10-1987
1004 viks CSE omputer Engg. 19-9-1982
1004 pooj IT Informtion Tehnology 23-9-1981
1002 reen IT Informtion Tehnology 6-5-1983
1004 vikas CSE omputer Engg. 19-9-1982
1004 pooja IT Information Technology 23-9-1981
1002 reena IT Information Technology 6-5-1983
In this example, the tr command translates the first character in the characterset1 into the
first character in the characterset2 and so on. The pipe symbol is used to take the input
from the specified file.
Option available with tr is
• -d option: This will delete the character specified in the character set from the input
but won't translate.
Multiple substitutions
If multiple changes need to be made to the same file, use the following options.
1) Using -e
[root@localhost ~]# sed -e 's/mango/litchi/' -e 's/apple/guava/' fruits.txt
litchi 1kg
orange 12pcs
guava 5kg
kiwis 1kg
bananas 24pcs
grapes 5kg
Global substitutions
Suppose the contents of file contain more than one occurrence of the word to be changed
and you want to replace all those with single command, then use the following method.
Syntax: sed 's/{previous data}/{current data}/g' <filename>
Example:
[root@localhost ~]# sed ' s/1kg/5kg/g' fruits.txt
mango 5kg
orange 12pcs
apple 5kg
kiwis 5kg
bananas 24pcs
grapes 5kg
In above example, it will search for all 1kg words and then replace all those words with
5kg.
[root@localhost ~]# sed ' s/1kg/5kg/g
> s/12pcs/24pcs/g' fruits.txt
mango 5kg
orange 24pcs
apple 5kg
kiwis 5kg
bananas 24pcs
grapes 5kg
In above example, it will search for all 1kg and 12pcs words and then replace all those
words with 5kg and 24 pcs respectively.
Restricted substitution
For applying substitution on restricted number of lines, we specify the line numbers.
[root@localhost ~]# sed '1,4 s/1kg/2kg/' fruits.txt
mango 2kg
orange 12pcs
apple 5kg
kiwis 2kg
bananas 24pcs
grapes 5kg
In above example, "1kg" is substituted with "2kg" only in the first and fourth line of the
fruits.txt output.
gawk
This is programmable filter available in Linux. gawk is useful for manipulating files that
contain columns of data on a line by line basis.
Syntax: gawk '{pattern action}' {file-name}
gawk is used for the following purposes.
Field Selection
There are some predefined variables which can be used for the purpose of field selection.
$0 is a special variable of gawk, which print entire record or fields.
$1 is used to print the first field
$2 is used to print the second field and so on.
Examples:
[root@localhost ~]# gawk '{print $2}' staff.doc
tajinder
vipul
krishan
vikas
pooja
reena
This example is used to print the second field in the staff.doc file.
[root@localhost ~]# gawk '{print $0}' staff.doc
1001 tajinder IT Information Technology 19-02-1979
1005 vipul CSE computer Engg. 4-10-1984
1006 krishan COM commerce 6-10-1987
1003 vikas CSE computer Engg. 19-9-1982
1004 pooja IT Information Technology 23-9-1981
1002 reena IT Information Technology 6-5-1983
The special variable $0 prints the complete record in the above example.
Pattern Matching
general syntax:- gawk '/pattern/{action}' <Filename>
[root@localhost ~]# gawk '/IT/ {print}' staff.doc
1001 tajinder IT Information Technology 19-02-1979
1004 pooja IT Information Technology 23-9-1981
1002 reena IT Information Technology 6-5-1983
In this example, gawk searches for the pattern “IT” in the file staff.doc and displays the
resulting lines.
if condition in gawk
General syntax of if condition is as follows:
Syntax:
if ( condition )
{
Stmt 1
Stmt 2
Stmt N
}
else
{
Stmt 1
Stmt 2
Stmt N
}
Example:
[root@localhost ~]# cat>check
{
if($1>1003)
{
print "Editable records\n" $0;
}
else
{
print "non-editable Records\n" $0 ;
}
}
[root@localhost ~]# gawk -f check staff.doc
non-editable Records
1001 tajinder IT Information Technology 19-02-1979
Editable records
1005 vipul CSE computer Engg. 4-10-1984
Editable records
1006 krishan COM commerce 6-10-1987
Editable records
1003 vikas CSE computer Engg. 19-9-1982
Editable records
1004 pooja IT Information Technology 23-9-1981
non-editable Records
1002 reena IT Information Technology 6-5-1983
In this example, the if condition checks for those records which satisfies the condition
($1>1003) and print the resultant lines with a message “Editable records” and according
to else part, the other records are printed with a message”non-editable records”
Loops in gawk
For loop and while loop are used for looping purpose in gawk.
Syntax of for loop
Syntax:
for (initialization; condition; incr/decr)
{
Stmt 1
Stmt 2
Stmt N
}
Statement(s) are executed repeatedly while the condition is true. Before the first iteration,
we initialize variables for the loop. After each iteration of the loop, we
increment/decrement a loop counter.
Example:-
[root@localhost ~]# cat >check1
{
for(i=1;i<3;i++)
{
printf "%s\n ",$0;
}
for (j=1;j<=79;j++)
{
printf "*";
}
}
[root@localhost ~]# gawk -f check1 staff.doc
1001 tajinder IT Information Technology 19-02-1979
1001 tajinder IT Information Technology 19-02-1979
**********************************************************************
1005 vipul CSE computer Engg. 4-10-1984
1005 vipul CSE computer Engg. 4-10-1984
**********************************************************************
1006 krishan COM commerce 6-10-1987
1006 krishan COM commerce 6-10-1987
**********************************************************************
1003 vikas CSE computer Engg. 19-9-1982
1003 vikas CSE computer Engg. 19-9-1982
**********************************************************************
1004 pooja IT Information Technology 23-9-1981
1004 pooja IT Information Technology 23-9-1981
**********************************************************************
1002 reena IT Information Technology 6-5-1983
1002 reena IT Information Technology 6-5-1983
**********************************************************************
In above example, first for loop will print all record twice and second for loop will pad *
symbol between the consecutive records.
Syntax:
initialize ;
while (condition)
{
Stmt 1
Stmt 2
Stmt N
Incr/decr
}
Example
[root@localhost ~]# cat >check1
BEGIN {print "Staff ID NAME"}
{
i=1;
while(i<3)
{
printf "%s ",$i;
i++;
}
printf "\n";
}
[root@localhost ~]# gawk -f check1 staff.doc
Staff ID NAME
1001 tajinder
1005 vipul
1006 krishan
1003 vikas
1004 pooja
1002 reena
Functions
gawk provides 2 types of functions.
• Built-in function
• User-defined Functions
Some of the built-in functions are as follow.
1) Numeric Functions
gawk has the following built-in arithmetic functions:
atan2(y, x) Returns the arctangent of y/x in radians.
cos(expr) Returns the cosine of expr, which is in radians.
exp(expr) The exponential function.
int(expr) Truncates to integer.
log(expr) The natural logarithm function.
rand() Returns a random number N, between 0 and 1, such that 0 ≤ N < 1.
sin(expr) Returns the sine of expr, which is in radians.
sqrt(expr) The square root function.
2) String Functions
Gawk has the following built-in string functions:
length([s]) :Returns the length of the string s, or the length of $0 if s is not supplied.
sub(r, s [, t]) : Just like gsub(), but only the first matching substring is replaced.
substr(s, i [, n]): Returns the at most n-character substring of s starting at i. If n is
omitted, the rest of s is used.
tolower(str): Returns a copy of the string str, with all the upper-case characters in str
translated to their corresponding lower-case counterparts. Non-alphabetic characters are
left unchanged.
toupper(str) :Returns a copy of the string str, with all the lower-case characters in str
translated to their corresponding upper-case counterparts. Non-alphabetic characters are
left unchanged.
3) Time Functions
systime() Returns the current time of day as the number of seconds since the Epoch
(1970-01-01 00:00:00 UTC on POSIX systems).
User-defined functions
Functions in AWK are defined as follows:
Syntax: function name (parameter list) {statements}
Functions are executed when they are called from within expressions in either
patterns or actions. Actual parameters supplied in the function call are used to instantiate
the formal parameters declared in the function. Arrays are passed by reference; other
variables are passed by value. Since functions were not originally part of the AWK
language, the provision for local variables is rather clumsy: They are declared as extra
parameters in the parameter list. The convention is to separate local variables from real
parameters by extra spaces in the parameter list.
Example:
[root@localhost ~]# gawk 'BEGIN {header()}\
function header()
{
printf "Employee Details\n"
}
function footer()
{
printf "...this is the end of file...\n"
}
{printf "%s \n", $0}
END { footer() }' staff.doc
Employee Details
1001 tajinder IT Information Technology 19-02-1979
1005 vipul CSE computer Engg 4-10-1984
1006 krishan COM commerce 6-10-1987
1003 vikas CSE computer Engg. 19-9-1982
1004 pooja IT Information Technology 23-9-1981
1002 reena IT Information Technology 6-5-1983
...this is the end of file...
The statements written in the BEGIN section are now executed within a user defined
function header and same is applied to the END section. A call to the function is made in
the BEGIN and the END part of the command.
Chapter 5
Linux Basics
5.1 LINUX FILE SYSTEM
Directory
Use to store this kind of files
Name
All your essential program (executable files) which can be use by most of
/bin
the user are store here. For e.g. vi, ls program are store here.
All super user executable (binaries) files are store which is mostly used
by root user . As mentioned in Red Hat Linux documentation: "The
/sbin
executables in /sbin are only used to boot and mount /usr and perform
system recovery operations."
Your sweet home. Mostly you work here. All the user have their own
/home
subdirectory under this directory.
Configuration file of your Linux system are here. For e.g. smb.conf -
Samba configuration file. It may contained sub directories like xinetd.d
/etc
or X11 which contains more configuration files related to particular
application or program..
When your system crashes, this is the place where you will get your files.
For e.g. You have shutdown your computer without unmounting the file
system. Next time when your computer starts all your 'fsck' program try
/lost+found
to recover you file system, at that time some files may stored here and
may be removed from original location so that you can still find those file
here.
Mostly the file(s) stored in this directory changes their size i.e. variable
/var data files. Data files including spool directories and files, administrative
and logging data, and transient and temporary files etc.
Central location for all your application program, x-windows, man pages,
documents etc are here. Programs meant to be used and shared by all of
the users on the system. Mostly you need to export this directory using
NFS in read-only mode. Some of the important sub-directories are as
follows:
/usr bin - sub-directory contains executables
sbin - sub-directory contains files for system administration i.e. binaries
include - sub-contains C header files
share - sub-contains contains files that aren't architecture-specific like
documents, wallpaper etc.
X11R6 - sub-contains X Window System
All shared library files are stored here. This libraries are needed to
/lib
execute the executable files (binary) files in /bin or /sbin.
/tmp Temporary file location
Special Device files are store here. For e.g. Keyboard, mouse, console,
/dev
hard-disk, cdrom etc device files are here.
Linux divides its physical RAM (random access memory) into chucks of memory called
pages. Swapping is the process whereby a page of memory is copied to the preconfigured
space on the hard disk, called swap space, to free up that page of memory. The combined
sizes of the physical memory and the swap space are the amount of virtual memory
available.
Swapping is necessary for two important reasons. First, when the system requires more
memory than is physically available, the kernel swaps out less used pages and gives
memory to the current application (process) that needs the memory immediately. Second,
a significant number of the pages used by an application during its startup phase may
only be used for initialization and then never used again. The system can swap out those
pages and free the memory for other applications or even for the disk cache.
However, swapping does have a downside. Compared to memory, disks are very slow.
Memory speeds can be measured in nanoseconds, while disks are measured in
milliseconds, so accessing the disk can be tens of thousands times slower than accessing
physical memory. The more swapping that occurs, the slower your system will be.
Sometimes excessive swapping or thrashing occurs where a page is swapped out and then
very soon swapped in and then swapped out again and so on. In such situations the
system is struggling to find free memory and keep applications running at the same time.
In this case only adding more RAM will help.
Linux has two forms of swap space: the swap partition and the swap file. The swap
partition is an independent section of the hard disk used solely for swapping; no other
files can reside there. The swap file is a special file in the file system that resides amongst
your system and data files.
To see what swap space you have, use the command swapon -s. The output will look
something like this:
Each line lists a separate swap space being used by the system. Here, the ‘Type’ field
indicates that this swap space is a partition rather than a file, and from ‘Filename’ we see
that it is on the disk sda5. The ‘Size’ is listed in kilobytes, and the ‘Used’ field tells us
how many kilobytes of swap space has been used (in this case none). ‘Priority’ tells
Linux which swap space to use first. One great thing about the Linux swapping
subsystem is that if you mount two (or more) swap spaces (preferably on two different
devices) with the same priority, Linux will interleave its swapping activity between them,
which can greatly increase swapping performance.
To add an extra swap partition to your system, you first need to prepare it. Step one is to
ensure that the partition is marked as a swap partition and step two is to make the swap
file system. To check that the partition is marked for swap, run as root:
Replace /dev/hdb with the device of the hard disk on your system with the swap partition
on it. You should see output that looks like this:
Superblock
Each file system is different and they have type like ext2, ext3 etc. Further each file
system has size like 5 GB, 10 GB and status such as mount status. In short each file
system has a superblock, which contains information about file system such as:
File system type
Size
Status
Information about other metadata structures
If this information lost, you are in trouble (data loss) so Linux maintains multiple
redundant copies of the superblock in every file system. This is very important in many
emergency situations, for example you can use backup copies to restore damaged primary
super block. Following command displays primary and backup superblock location on
/dev/sda3:
[root@localhost ~]# dumpe2fs /dev/hda3 | grep -i superblock
Linux file system inodes
Each object in the file system is represented by an inode. A Linux file has following
attributes:
=> File type (executable, block special etc)
=> Permissions (read, write etc)
=> Owner
=> Group
=> File Size
=> File access, change and modification time
=> File deletion time
=> Number of links (soft/hard)
=> Extended attribute
=> Access Control List (ACLs)
All the above information stored in an inode. inode identifies the file and its attributes .
Each inode is identified by a unique inode number within the file system. Inode is also
known as index number.
An inode is a data structure Linux file system such as ext2 or ext3. An inode stores basic
information about a regular file, directory, or other file system object.
mount command
Now to mount device (CDROM,FLOPPY DISK etc) use following mount command
Syntax : mount option {device} {mount-point}
Option:
-t type To specify file system being mounted.
For MS-DOS use msdos
For Windows 9x use vfat (Long file name support under windows 95/NT etc)
iso9660 type is default and used by cd-roms.
-v it’s called verbose mode which gives more information when you mount
the file system.
Unfortunately, fdisk doesn't give you any output to tell you it did it correctly. Just reboot
and you'll go straight into Win98, with lilo all removed.
The next step is to configure GRUB by properly editing the menu.lst file. You can find
the GRUB Stage2 configuration file at /boot/grub/menu.lst.
Configuring GRUB
GRUB configuration is all done through a configuration file located in
[root@localhost ~]#vi /boot/grub/grub.conf.
default=0
timeout=10
splashimage=(hd1,2)/grub/splash.xpm.gz
password --md5 $1$opeVt0$Y.br.18LyAasRsGdSKLYlp1
title Red Hat Linux
password --md5 $1$0peVt0$Y.br.18LyAasRsGdSKLYlp1
root (hd1,2)
kernel /vmlinuz-2.4.18-14 ro root=LABEL=/
initrd /initrd-2.4.18-14.img
title Windows XP
password --md5 $1$0peVt0$Y.br.18LyAasRsGdSKLYlp1
rootnoverify (hd0,0)
chainloader +1
Other proprietary operating system like Windows can be loaded by a process called chain
loading, as follow (without specifying the kernel or other such parameters-we will only
specify the partition in which it is installed):
The initial boot process
When GRUB initially loads, like LILO it loads its first stage from the MBR. Once this
has loaded, it then enters an intermediate stage between the common boot loader stages
one and two (or for argument's sake, Stage 1.5). Stage 1.5 is present to enable regular file
system access to the GRUB configuration files in /boot/grub rather than accessing using
disk blocks. We then enter stage two of the boot loader where GRUB loads the grub.conf
file.
Handling boot failures and MBR overwriting
A usual scenario all dual- boot (Linux and Windows) users face is when installing
Windows after Linux; this causes MBR (the GRUB boot loader) to be overwritten by
Windows. Following this, the computer straight away boots Windows. Without
displaying the entries for the other installed operating systems- this is why it is always
advisable to install Linux after Windows. However, even if you’ve encountered a
situation where you’ve lost GRUB, you can fix it easily.
Collect some GNU. Linux live CD like Knoppix and boot from it. If the live CD display
a GRUB menu, it is even easier. Press C to enter the GRUB command line:
The output of the find command in the above snippet says that it has found two Linux
installations on the system. Now, in order to install GRUB from either of this Linux
installation, run the following set of commands:
Succeeded
Running “install /boot grub/stage (hd0)1+19 p (hdo,4) /boot/grub stage2 /boot grub
grub.conf”…succeeded done.
Grub>
That is. Your Grub is now restored back into the MBR. Alternately, you can boot into the
live CD and get a root prompt:
# mkdirt /mnt/fixroot
# mounts /dev/sda6 /mnt/fixroot
# mount –bind/dev/ /mnt/ fixroot/dev
# grub- installs /dev/sda
What have to be done above is as follows. Mount the route device (/dev/sda6)
to/mnt/fixroot. The devices currently available to the live system are then bound to/dev/of
of the route partition (dev/sda6) at /mnt/fixroot/dev. Finally, we temporarily change-root
to the execute grub-install to fix MBR. (Of course, do not forget to change/dev /sdas5 to
the correct Linux partition on your system.).
Now, append the MD5 hash to your/boot/grup/menu. 1st file as follows, at the top of the
file after the command texts:
#menu1st-see: grup (8), info grup, update-grup (*)
# grup-install (*), grub-floppy (*),
# grub-md5-crypt, /usr/share/doc/grub
# And /user/share/doc/grub-doc/
Password—md5 $1$tlwkk$k2zwli3kmzjssimf7k.sh/
If GRUB is password protected, you won’t be able to enter the edit more by pressing e
.Rather; you have to enter the password by pressing P First and E after word to edit the
menu.
Advantages of GRUB over LILO
LILO is older and less powerful. Originally LILO did not include a GUI menu choice
(but did provide a text user interface). To work with LILO an administrator has many
tasks to perform in addition to editing the configuration files.
GRUB is a bit easier to administer because the GRUB loader is smart enough to locate
the /boot/grub/grub.conf file when booting. An administrator only needs to install GRUB
once, using the "grub-install" utility. Any changes made to grub.conf will be
automatically used when the system is next booted. In contrast, any changes made to
lilo.conf are not read at boot time. The MBR needs to be "refreshed."
Like GRUB does, LILO has no interactive command interface and does not support
booting from a network. If LILO MBR is configured correctly, the LILO system becomes
unbootable. If the GRUB configuration file is configured incorrectly, it will default to the
GRUB command-line interface without risking of making the system unbootable.
LILO and GRUB allows users—the root users—to boot into single-user mode. Both have
a password protection feature with a difference. While GRUB allows for MD5 encrypted
passwords, LILO manages only text passwords, which anyone can read from the lilo.conf
file with the command vi /etc/lilo.conf.
LILO has no interactive command interface, whereas GRUB does.
LILO does not support booting from a network, whereas GRUB does.
LILO stores information regarding the location of the operating systems it can to load
physically on the MBR. If you change your LILO config file, you have to rewrite the
LILO stage one boot loader to the MBR. Compared with GRUB, this is a much more
risky option since a mis configured MBR could leave the system unbootable. With
GRUB, if the configuration file is configured incorrectly, it will simply default to the
GRUB command-line interface
Unlike LILO's configuration file, grub.conf is read at boot time, and the MBR does not
need to be refreshed when this is changed.
Context switches
Processes
Scheduler
Apart from choosing a process, it is also the responsibility of the scheduler to save the
context of the current process and restore the context of next process scheduled to run.
This called context switch. This is essential for the proper functioning of the processes.
The kernel should make sure that context switching is invisible to user. Figure 1 depicts a
scenario where there are many processes contending for process time and scheduler
chooses one based on the scheduling policy.
Linux is a multi-purpose operating system. Though operating system is specific to
platform, Linux is not. Don’t misinterpret this statement. With other operating systems,
for example, the code for Intel processor will not work for SPARC architecture. But the
good thing about Linux is that it continuously ported for many hardware platforms. The
open source nature of Linux is the main reason for this. Another important reason is the
enthusiasm of kernel developers and most importantly Linux users.
Linux powers a wide range of systems, right from small systems like mobile phones and
digital organizers to huge ones like production server clusters and supercomputer
clusters. Since there is difference in the various types of systems it supports, the
application that runs on these different kinds of systems should also be different. The
nature of applications that run on Linux varies from highly demanding real time
processes to the ones that dump output of the command ls, which are not that demanding.
We can classify the processes into three types:
• CPU bound or CPU intensive processes
• Input / output (I/O) bound processes
• Real time processes
Real-time processes:These are highly demanding and all the critical operation come
under this category. A typical example would be an embedded system that monitors the
heartbeat of a patient. These processes demand processor time. The moment they come to
running state they need the CPU. Deferring the scheduling of such processes can’t be
entertained. So we have now segregated the processes and, by doing so, understood that
though these processes are different, they still have to co-exists and run successfully.
Keeping this in mind, let us now try and understand the Linux scheduler.
In this section, we will discuss Linux scheduling policy and how scheduling decisions
improve the Linux system performance.
1) Linux has priority based scheduling. Higher priority processes are processed
before lower priority processes.
2) Interactive processes are given more priority than a CPU bound process. This
improves the interactivity of system.
3) Linux has support for real time processes. Linux is a soft real system. All real
time processes are serviced before normal, conventional processes.
Based on this, Linux scheduling has three scheduling classes. These are
SCHED_FIFO
This scheduling class for real time processes. When the kernel puts the puts the
processes of the SCHED_FIFO class on the processor, it never takes it back until a
real time process of higher priority process arrives or it voluntarily relinquishes the
processor. The process is not taken back even if a real time process of same priority
arrives.
SCHED_RR
This is same as first one, except that the processes are chosen on round robin basis
if they are of same priority. This class is also used by real time processes.
SCHED_OTHER
This is the scheduling class for normal, non real time processes.
The scheduling of the processes is based on the scheduling class.
In order to burn the ISO’s into a CD, you must have a third-party CD burning program.
The native burner which is built into Windows XP DOES NOT have the ability to do
this. It will only copy the ISO onto the cd which does you no good (Look at the very
bottom of this tutorial for a brief explanation on this).
The final preparation step is to back up all your files(Don't forget your e-mails!! - I lost
over a thousand e-mails from my first semester because I forgot to back them up!).
Pop in the XP installation CD and restart. When your Computer’s start up screen comes
up, enter the BIOS setup by pressing the necessary key(s). Set it up to have your
computer boot from your CD drive. When the CD boots up, you’ll be greeted with the
standard Windows XP set-up screen.
The next step is to use the fdisk partitioning utility and carve your hard drive into
partitions. Fdisk comes with XP. After you ok the installation for the first time it willlet
you delete your current hard disk and partition it. How you partition your hard disk is up
to you and what your system can handle. I did the following on my 40 GB hard drive:
I decided to make the Data and Files partition FAT32; because that way both Linux and
XP can read and write to it (Linux can read from NTFS, but writing to it is still
“experimental” and not suggested). After you partition the hard drive you format the
partition XP on using NTFS (make sure that your XP partition is the FIRST partition).
Continue with the XP setup and finish installing. Once you’re done, you can format the
other partitions (not necessary for the Linux partition though) by going to Start ->
Control Panel -> Administrative Tools -> Computer Management. There are tools in
there that you can use to format your partitions and make them recognizable and usable
in Windows.
Partitioning, Formatting, and Installing Linux:
The Linux install is only slightly more complicated, but is faster (~20min). Pop-in the 1st
Linux CD and restart again. Your system should still be set to boot from CD, so the
Linux installation screen should come up. You want to do just an install. In Redhat 7.2
this brings up the installation GUI for Linux. When it asks you what kind of installation
you would like to perform you want to select “custom” or “expert” (custom is the easier
of the two, only use expert if you are sure that you know what you are doing!), since
you’ll need to tell Linux what partition to install on.
Setup will eventually ask you what program you want to use to partition your hard drive.
I chose to use Disk Druid. It’s a pretty easy utility to use and it has a GUI (unlike fdisk
which is command line). Linux will recognize your Windows partitions and show them.
If Windows decided to format your Linux partition to FAT16 (mine did for some weird
reason…) just delete it. Out of the free space left on your hard drive you need to make the
following partitions:
Once this is done, you can continue through the rest of the setup, just make sure that
when you reach the point of what Boot loader you want to use, pick GRUB and make
sure it installs to the MBR(Master Boot Record). This will cause Linux to boot instead of
XP the next time your computer boots from the hard disk.
Once your done picking and choosing what you want installed along with the Linux OS,
setup will do the rest for you. Make sure you make a user account for yourself other than
“root” when prompted by the Linux setup, because when you are logged into the “root”
account you can do anything and everything to the partition Linux resides on, including
DELETING THE WHOLE PARTITION by accident.
Once Linux is finished loading, bring up the Command Line Shell .Once the Command
Shell appears, you need to navigate to the following directory and file:
/etc/grub.conf
If you’ve never used the command line interface in Linux before , go to the “Sessions”
button and click on the “Root Midnight Commander” (the non-“Root” version won’t
allow you to edit the file). This will bring up a very basic GUI (similar to the BIOS setup
in use) that will allow you to easily navigate your Linux files.
Once you open up the file, either through the command line or through Midnight
Commander, go all the way down to the bottom of the file and add the following lines
after the rest of the lines in the file:
title Windows XP
[TAB]root (hd0,0)
[TAB]makeactive
[TAB]chainloader +1
PLEASE NOTE that the word TAB inside the brackets indicates where you should indent
with a TAB. Make sure that you type the bolded lines in EXACTLY as written above
with the spaces and capitalizations all correct. Save it and exit. The next time you restart
and the GRUB boot loader comes up, Windows XP should be listed under Linux. Just
select it with the keyboard and hit enter. Windows XP should boot up and your system is
now dual-booting Windows XP and Linux!! If the Windows XP title does not appear on
your GRUB boot loader screen then you know that you did it wrong. Just go into Linux
under your root account, and make sure the added lines look EXACTLY like the bolded
lines above. There are NO semi-colons or anything ending the lines.
Requirements:
You need a windows 98 startup disk or windows 98 bootable floppy .
How to do it:
1. Boot up in Windows xp.
2. Start>>control panel>>administrative tools>>computer management
3. Go to disk management under “storage”
4. Select your hard disk and then the Linux partition.
5. Delete the Linux partition this will delete Linux and grub.
6. Now reboot your laptop with windows 98start up disc or floppy and type the command
“fixmbr” .
7. Above command will repair your boot loader and rewrite ntldr which will replace
corrupted grub.
8. That’s it done now boot your laptop or desktop normally it will be booted by default in
windows xp.
Linux based solution: boot Linux using first cd. Type Linux rescue.
Press <Enter> to exit assembly mode, take a deep breath - and press “g” to execute, then
“q” to quit “debugs". Your HD is now in a virgin state, and ready for partitioning and
installation.
1)To create a LVM we have to first create a partition, after that create physical
volume from this partition
[root@localhost]# pvcreate /dev/sda6(6 is partition no)
2)Now create a volume group to use this physical volume.
[root@localhost] #vgcreate vg0 /dev/sda6 (vg0 is volume group name
3) Create a lvm partition from this.
[root@localhost]# lvcreate –L 100m –n lv0 /dev/vgo
(100m is size of Lvm and lvo is name of lvm)
4)Now format this LVM usinf mkss.ext3
[root@localhost] mkfs.ext3 /dev/vg0/lv0
5) Create a mounting point for this partition
[root@localhost] mount /dev/vg0/lvo /mnt
This mount will be temporary
To mount it permanent open vi /etc/fstab file
[root@localhost] vi /etc/fstab
/dev/vgo/lvo /mnt ext3 defaults 0 0
Finally lvm will be created
6) To view lvm, volumegroup.physical volume
[root@localhost]# lvdispaly
[root@localhost]# vgdisplay
[root@localhost]# pvdisplay
5.10 RAID
RAID, an acronym for Redundant Array of Independent Disks (formerly Redundant
Array of Inexpensive Disks), is a technology that provides increased storage reliability
through redundancy, combining multiple relatively low-cost, less-reliable disk drives
components into a logical unit where all drives in the array are interdependent.
Creating a raid device
1)Firstly verify all the previously created raid partitions.
[root@localhost] mdam - -detail /dev/md0
Or
[root@localhost] cat /proc/mdstat
2) Raid devices are basically used for databackup. Data will be safe even if any hard
disks get fail from raid devices.
To test it first copies some data in /data directory. Which is mount point for raid devices?
[root@localhost]# cp * /data
[root@localhost]# ls /data
3) Now assume one hard disk form raid device gets fail. This can be done using mdam
command with – fail options.
[root@localhost]# mdam /dev/mdo - -fail /dev/sd7
4) We can verify the fail device status via mdam command with - -details switch also
[root@localhost]# mdam - -detail /dev/md0
6) At this point we have understood what exactly raid device do? raid device keep
your data safe even if hard disk got crashed. It’s give you enough time to replace
faulty hard disk without losing data.Now remove our faulty devices.
[root@localhost]# mdam /dev/md0 - -remove /dev/sda7
8)Finally we have created raid device and changed faulty hard disk with new one.
Deleting a raid device
Umount the raid partition from /data directory
[root@localhost] #umount /data
Now stop the /mdo devices and remove it from mdam
[root@localhost] #mdam - -stop /dev/md0
[root@localhost] #mdam - -remove /dev/md0
Remove the entry from /etc/fstab file.
[ root@localhost] #vi /etc/fstab
And remove the entry.
Finally we have deleted a raid device partition.
Chapter 6
Process Management
6.0 PROCESS MANAGEMENT
A process is a program in execution. Every time you invoke a system utility or an
application program from a shell, one or more "child" processes are created by the shell
in response to your command. All LINUX processes are identified by a unique process
identifier or PID. An important process that is always present is the init process. This is
the first process to be created when a LINUX system starts up and usually has a PID of 1.
All other processes are said to be "descendants" of init.
A Simple Process
The above fig. illustrate that firstly the program is load into memory after that it can be
run on a typical shell environment after that finally it can be exit. The part of the system
that managers the processes is called kernel.
Definition:
“A process is defined as an instance of a running program” Every program running on
your system is running in its own process. In fact every copy of every program has its
own process. For example if you startup an editor twice, without closing the first
invocation before starting the second, you will have two processes running that editor.
Basic Idea:
Most programs give rise to a corresponding process; usually have the same name as the
program itself. For example when you execute the grep command, a process named grep
is created; a program can also give rise to multiple processes. When you run a shell script
or a group of commands in a pipeline, you are running one job alright-but multiple
processes.
Attributes of a process:
A process has the following attributes associated with it:
1. PID(Process ID )
2. environment
3. Memory area
4. signal Handling
5. File Descriptions
6. Resource Scheduling
7. Security information
8. Synchronization
9. State
1. PID: Each process has a unique ID. It occurs only once when the process ID. It
occurs only once when the process is created and can be reused when system
remains online for a long time. The PID is the primary way of identifying a
process.
2. Memory area: Each process also has a Memory area associated with it. This
area holds:
i) The code for the program that is running in that process.
ii) The data (variables) for that particular program.
This code will fork. If the return value is 0, it means that the current process is the child
from the fork .If the value is not -1 it means that the fork was successful and return value
indicates the PID of the new process. On the other hand, if the value is -1 then the fork
was failed.
Output:
When you run this program, you will get two messages – one from the parent and one
from the child, because these are separate process:
$ . / ch12-1
HELLO FROM THE PARENT.I FORKED PROCESS 267
HELLO FROM THE CHILD PROCESS!
$ . / ch12-1
HELLO FROM THE CHILD PROCESS
HELLO FROM THE PARENT.I FORKED PROCESS 269
EXEC: The parent then overwrites the image it has just created with the copy of the
program that has to be executed. This is done with the exec system call and the parent is
said to be exec this process. No additional process is created here; the existing program’s
text and data areas are simply replaced (or overlap) with the ones of the new program.
This process has the same PID as the child that was just forked.
Working
Besides forking, you will often have a need to invoke other programs. This is done with
the family of functions. When you run exec, your process’s current image is replaced
with that of the new program.
Example: In this example, a program in which in which the program in the process is
#include<sdio.h>
#include<unistd.h>
int main(void)
{
printf(“Hello sample program \n”);
execlp(“ls”,”ls”,”/proc”,NULL);
printf(“This code run after exec call \n”);
printf(“You should never see the message when exec failed \n”);
Return 0 ;
}
This is fairly simple program. it starts out by displaying a message on the screen. Then it
calls one of the exec families of functions.
execlp : the ‘l’ in the name means to use an argument list passed to it . And the ‘p’ means
to search a path.
Output: when you run this:
$ . / ch12-1
Hello,this is a sample program
1 198 250 267 323 347 for file system mem inf slab inf
114 2 255 268 324 348 404 fs mmc slat
Details Of exec ( ): The system provides you with many options for executing new
programs. The man pages list the following:
p- execlp() and execpvp() : search the path for the file if it can not be located immediately
llfunctions: the three ll functions execl(),execlp(),execle() takes a list of the argument for
the program on the command line. After last argument, you must specify the special
values NULL . for instance you might use the following to invoke ls:
execl(“/bin/ls”, “/bin/ls”,”l”,”/etc”,NULL);
vv functions: The execv(),execvp(),execve() use a pointer to an array of strings for the
argument list. This is the same format as is passed into your program in argv in main().
The last item must be NULL.
e-functions: execle() and execve() enables you to customize the specific environment
variables received by your child process .
WAIT: The parent then executes the wait system call to keep waiting for the child
process to complete when the child has completed execution; it sends a termination signal
to the parent. The parent is then free to continue with its other functions.
Working: problem is that, when a process exits, its entry in the process table does not
completely go away. This is because the operating system is waiting for a parent process
to fetch some information about why the child process expired. This could include a
return value, a signal, or something else along those lines. A process whose program
terminated but still remains because its information was not yet collected is dubbed a
zomble process.
Example:
#include<sdio.h>
#include<unistd.h>
#include<sys/types.h>
int main(void)
{
pid_t pid;
pid = fork();
if ( pid= =0 )
{
printf(“Hello from Child process ! \n”);
printf(“The Child is existing Now \n”);
}
else if ( pid != = -1 )
{
printf(“Hello from the parent,pid %d \n”,getpid( ));
printf(“The parent has forked process %d \n”,pid);
sleep(60);
printf(“the parent is existing Now \n”);
}
else
{
printf(“There was an Error with forking \n”);
}
}
There is now a sleep call in the parent to delay its exit for a minute so you can
examine the state of the system’s process table in another window. when you run the
program :
$ . / ch12-3
Hello from the parent, pid 267
Hello from Child process!
The Child is existing now
The parent has forked process 269
Now in a separate window or terminal. Take the process ID of the child. In this case it is
269. Find its entry with a command like this:
$ ps aux / grep / grep –v grep
Puneet 269 0.0 0.0 0 opts /0 z 08:18 0:00
State of the process is indicated as z – that is zoom able process.
Details of Wait:
There are a number of variants of the wait functions in linux, just as there are a no. of
variants of the exec calls. Each call has its own special feature and syntax. The various
wait functions are declared as follows:
1) pid_t wait ( int *status)
2) pid_t waitpid ( pid_t pid , int *status , int options);
3) pid_t wait3 ( int *status , int options , struct rusage *rusage);
4) pid_t wait4 ( pid_t pid , int *status , int options , struct rusage *rusage);
The first two calls require system/types.h and system/wait.h . And last two requires
system/resources.h . Each of these functions returns the PID of the process that exited, 0
if they were told to be non blocking and no matching process was found , and -1 if there
was an Error.
6.4 PROCESS STATES
The state field of the process descriptor describes the current condition of the process.
Each process on the system is in exactly one of five different states. This value is
represented by one of five flags:
TASK_RUNNING The process is runnable; it is either currently running or on a run queue
waiting to run. This is the only possible state for a process executing in user-space; it can
also apply to a process in kernel-space that is actively running.
TASK_INTERRUPTIBLE The process is sleeping (that is, it is blocked), waiting for some
condition to exist. When this condition exists, the kernel sets the process's state to
TASK_RUNNING. The process also awakes prematurely and becomes runnable if it
receives a signal.
TASK_UNINTERRUPTIBLE This state is identical to TASK_INTERRUPTIBLE except
that it does not wake up and become runnable if it receives a signal. This is used in
situations where the process must wait without interruption or when the event is expected
to occur quite quickly. Because the task does not respond to signals in this state,
TASK_UNINTERRUPTIBLE is less often used than TASK_INTERRUPTIBLE.
TASK_ZOMBIE—The task has terminated, but its parent has not yet issued a wait4()
system call. The task's process descriptor must remain in case the parent wants to access
it. If the parent calls wait4(), the process descriptor is deallocated.
TASK_STOPPED—Process execution has stopped; the task is not running nor is it
eligible to run. This occurs if the task receives the SIGSTOP, SIGTSTP, SIGTTIN, or
SIGTTOU signal or if it receives any signal while it is being debugged.
6.5 PROCESS CREATION
A new process is created because an existing process makes an exact copy of itself. This
child process has the same environment as its parent, only the process ID number is
different. This procedure is called forking.
After the forking process, the address space of the child process is overwritten with the
new process data. This is done through an exec call to the system.
The fork-and-exec mechanism thus switches an old command with a new, while the
environment in which the new program is executed remains the same, including
configuration of input and output devices, environment variables and priority. This
mechanism is used to create all UNIX processes, so it also applies to the Linux operating
system. Even the first process, init, with process ID 1, is forked during the boot
procedure in the so-called bootstrapping procedure.
There are a couple of cases in which init becomes the parent of a process, while the
process was not started by init, as we already saw in the pstree example. Many
programs, for instance, demonize their child processes, so they can keep on running when
the parent stops or is being stopped. A window manager is a typical example; it starts an
xterm process that generates a shell that accepts commands. The window manager then
denies any further responsibility and passes the child process to init. Using this
mechanism, it is possible to change window managers without interrupting running
applications.
Every now and then things go wrong, even in good families. In an exceptional case, a
process might finish while the parent does not wait for the completion of this process.
Such an unburied process is called a zombie process.
The return codes can then be interpreted by the parent, or in scripts. The values of the
return codes are program-specific. This information can usually be found in the man
pages of the specified program, for example the grep command returns -1 if no matches
are found, upon which a message on the lines of "No files found" can be printed. Another
example is the Bash built-in command true, which does nothing except return an exit
status of 0, meaning success.
6.7 EXPLORING THE PROCESS FILE SYSTEM
Linux provides us with a mechanism called the proc file system through which we can
get all sorts of information from the kernel, at runtime.
Process named after its process ID (PID). It also provides an interface to pass control
options to the kernel at routine by writing into specific files that reside inside the /proc
directory. The files inside/ proc are created on the fly- exactly why it is called a virtual
file system -and can be viewed using tools such as cat, less, tail, head, etc. let us now
explore the proc file system.
Hardware status
Some files in the /proc directory give information about the hardware. These files can be
used to check your hardware configuration.
[root@localhost ~]# # cat /proc/meminfo
The/proc/meminfo file contains the information regarding the memory of the system. The
MemTotal field gives the amount of the total physical memory available on the system.
MemTotal , when subtracted by Memfree, will give the amount of physical memory
being used by the kernel.
[root@localhost ~]# cat /proc/cpuinfo
The above file starts with the processor field that gives us information about the
processor number followed by specific details about the processor. So for a dual core
processor, the whole information is displayed twice-first forprocessor0, and then for
processor1. we also get to check other handy information like the vendor ID, model
name, clock speed, cache size fields, etc. the fpu field indicates whether the floating –
point unit is present or absent in the processor.
[root@localhost ~]# cat/proc/devices
The /proc/devices file lists the registered character and the block devices drivers in the
system. The first column contains the major number of the devices drivers and the second
column contains the name of the device.
The /proc/ide/subdirectory contain information about all the kernel –registered IDE
devices. There is one directory for each IDE controller and asoft link for each IDE
devices pointing to the device directory.
[root@localhost ~]# cd / proc/ide
[root@localhost ~]# 1s – al
******************************
The drivers file gives the details of the IDE drivers with the version. The IDE controller
subdirectory (ide*/) contains information about the IDE channel in the channel file ,
chipset of IDE controller in the model file, the name of the partner controller in the
mate file and a subdirectory (/proc/ide/ide*/hd*) for the IDE devices. This subdirectory
can be looked up for the devices specific information, such as the type of media, model
number, devices settings and unique identifier of the devices.
The files listed above will provide you with a great deal of information regarding the
hardware.
System status
Apart from the hardware information, the /proc can be probed to know about the system
status.
The /proc/kcore file is the snapshot of the kernel in physical memory. Exploring kcore
provides sound knowledge about the processes running on the system. Listing the kcore
file under /proc shows that its size is not 0.
[root@localhost ~]# cd /proc
[root@localhost ~]# 1s -lh
***************************
The size of the kcore file is the size of kernel in memory. The file can only be accessed
by the root user. To view the kcore file, we have to use the following strings command:
[root@localhost ~] # head –n 100 /proc/kcore| Strings
Core
Core
vm1inux
root=/dev/hda5 vga= 0x317 resume =/dev /hda6 splash=silent showts
core
head
-terminal
20061115(prerelease) (SUSE Linux )
GCC: (GNU) 4.1.2 20061115 (prerelease)(SUSE Linux)
GCC: (GNU) 4.1.2 20061115 ( prerelease) (SUSE Linux)
<<Output truncated>>
The output contains the details about the kernel boot parameters (/proc/cmidline), the
release version of gcc. /proc/kcore can also be used to view details such as the files used
when a user logged in to bash shell.
[root@localhost ~]# head –n 100000 /proc/ kcore | Strings | grep bash
Lubumbashi
Rbash
/ etc/ bash.bashrc
~/.bash_profile
~/.bash_login
~/.bashrc
Use the ‘bashbug’ command to report bugs.
/use/local/lib/bashdb/bashdb-main.inc
~/.bash_history
[email protected]
Cannot allocate new file descriptor for bash input from fd %d
Save_bash_input : buffer already exists for new fd %d
GNU bash, version %( %s)
<< Output truncated>>
Note: - if while exploring kcore your terminal becomes unreadable, then you need to
stop the process (can be done by pressing ctrl+c) and use the ‘reset’ command.
Process status:
The /proc/<PID>/ are the numbered subdirectories corresponding to an actual process ID.
Process IDs can be viewed by executing ps –ae command from shell. Process details can
be obtained by looking at the associated file in the /proc/<PID>/ directory. To view the
details of your bash shell, execute the following commands
The /proc/<PID>/fd/ subdirectory contains the file descriptors used by the process.
Execute the cat command to start a process in one of the terminals. List the
/proc/<PID>/fd directory from another shell prompt
[root@localhost ~]#ps –ae
***********************************
[root@localhost ~]#ls –l /proc/***/fd
*************************
The 0, 1 and 2 are the links for the standard input, output and error device.
Tips:- The /proc/sys/kernel directory accounts for the general behavior of the kernel. It
also contains information related to the kernel. We can use the files in this directory for
administrative purposes, though only the root user can modify these files by using the
echo command. The contents of hostname, ostype and osrelease files are self-
explanatory.
[root@localhost ~]# hostname
ram
[root@localhost ~]# echo “mohan” > /proc/sys/kernel/hostname
[root@localhost ~]# hostnamemohan
The /proc/sys/kernel/panic files describe the action to be taken by the kernel on a kernel
panic. A 0 in this file indicates that there will be no auto reboot after a kernel panic,
whereas a non-zero numeric represents the time, in seconds, before an auto reboot. The
/proc/sys/kernel/pid_max file contains an integer defining the maximum number of PIDs
that can be issued by the kernel on the system. Likewise, administrators can restrict the
number of processes running on the system by echoing the required number of PIDs in
this file. The type of shutdown is defined by the ctrl + alt +Del file –if it is 1, then the
system will shutdown without un mounting the file system (in other words, an improper
shutdown); a 0 indicates clean shutdown. The entry in the /proc/sys/kernel/pty/nr file
gives the number of pts terminals in use, while the /proc/sys/kernel/pty/max file defines
the maximum number of pts terminals.
The /proc/sys/net directory contain network related information. Network configuration
can be changed during runtime by echoing into the corresponding file. For example, to
make your machine invisible to the network, type following commands:
Or, in order to make your Linux box forward IP packets and act as a router, you can
execute the following command
[root@localhost ~]# echo “1” > /proc/sys/net/ipv4/ip_forward
The packets received by your computer can be routed back to the originating system
(which may be outside your network) and thus leak your network information to
attacker’s .in order to safeguard your computer from such attacks, execute the following
command:
To avoid the kernel log files from becoming bulky with invalid responses or bad error
messages, execute the following command
The performance of a system with lots of TCP connections can be increased by lowering
the number of retries before closing a connection, execute the following command
[root@localhost ~]# echo “0” > /proc/sys/net/ipv4/tcp_orphan_retries
Source addresses verification for all the IP addresses on your Linux machine.
Execute the following command
[root@localhost ~]# echo “1” > /proc/sys/net/ipv4/conf/all/rp_filter
This is also known as reverse path filtering, and the above example echo 1 to rp_filter
File. This is considered a safeguard against IP spoofing attacks. Now kernel rejects even
valid packets if you have multiple network interfaces or multiple IP addresses on single
interfaces.
The /proc/acpi/ directory provide the ACPI (advance configuration and power interface)
related information. To check whether ACPI is activated or not by executing
Note:Changes made in /proc/sys/ directory are not permanent. The echoed values get lost
on a reboot. To make changes in the /proc/sys/ directory permanent, we have to make an
entry of ‘variable = value’ pair in the /etc/sysctl.conf file. For example, to enable packet
forwarding permanently on your system, make an entry like ‘net.ipv4.ip_forward = 0’ in
your /etc/sysctl.conf file. Then execute ‘sysctl –p’ as the root to load the values from the
updated file. But how can we predict the variables names?
Execute following
# truncate /pro/sys
#replace “/” with “.”
So, the /proc/sys/kernel/hostname file has the variable name kernel. hostname and
/proc/sys/net/ipv4/ip_default_ttl file has the variable name net.ipv4.ip_default_ttl for the
/etc/sysctl.conf file.
6.8 CRON
cron is the memory-resident scheduler daemon that can execute commands and scripts at
regular intervals. The jobs it runs are listed in a crontab file which is edited using the
crontab utility. It is a utility written by Brian Kernighan.Cron stores it's entries in the
crontab (cron table) file. This is generally located in your /etc directory. As well, each
user on your system can have their own crontab which would be stored in
/var/spool/cron/.
Field Meaning
1 Minute (0-59)
2 Hour (2-24)
3 Day of month (1-31)
4 Month (1-12, Jan, Feb, etc)
5 Day of week (0-6) 0 = Sunday, 1 = Monday etc or Sun, Mon, etc)
6 User that the command will run as
7 Command to execute
00 * * * * date >>/tmp/hourlytime.log
Save and exit. Now, back in the terminal, run the following commands:
#crontab cronjobs
#crontab -l
Environment settings
DISPLAY=:0
00 10 *** /usr/bin/gedit
DISPLAY environment variable line recommended on your crontab entry if you are
scheduling to run applications that need X (GUI); else, it will not work.
Example:
Take a look at the following sample cron job entry:
00 02 * * * /usr/bin/ktorrent
What does the entry mean?
• 00 – 0th minute
• 02 – 2nd hour
• * - any day of month
• * - any month
• * - any weekday
Execute /usr/bin/ktorrent at the 0th minute of 2 a.m., on any day of the month, any month,
any day of the week.
# Open gedit at 12 am
00 12 * * * gedit /home/staff.doc
To start downloads at 7 a.m. and stop them at 10 a.m., execute the following:
00 07 * * * cd/home/slynux/distros/; wget-c http:// example.com/ubuntu.iso
00 10 * * * killall wget –s 9
crontab commands
To remove crontab for a specific user:
[root@localhost ~]# crontab –u username –r
To know what tasks cron shall be executing you can use the following command
[root@localhost ~]# crontab -l
This command shall provide a detailed list of all the jobs that cron shall execute. It would
basically be showing you your crontab file. So you need to know the meaning of the 6
fields to make sense of the output
To remove the current crontab you can use the following command
[root@localhost ~]# crontab -r
This shall remove whatever entries you added to cron using your own crontab file.
To edit the crontab to enter or remove tasks type the following command
[root@localhost ~]# crontab -e
cron tips
To run a task every 5 hours
If you want to do the above then in the crontab file entry, in the hour field you can enter a
Step Value as follows '*/5' (without the inverted commas). This would cause the task to
be executed every 5 hours.
To run a task in the first 10 days of a month and then last 10 days of the month you can
use Ranges as follows
Enter '1-10,21-30' (without the inverted commas) in the 'Days' field.
To run a task every alternate day for the first 15 days of the month you can enter '1-15/2'
in the 'Days' field. This would run the task on the following days of the month
(1,3,5,7,9,11,13,15)
If you want to enter Comments, all you have to do is to add a # at the beginning of the
line. Remember comments are not allowed on the same line with a cron command. So
comments need to be entered on a separate line starting with a # (first character should be
#)
Chapter 7
Shell programming
Shell Prompt
The prompt, $, which is called command prompt, is issued by the shell. While the prompt
is displayed, you can type a command.
The shell reads your input after you press Enter. It determines the command you want
executed by looking at the first word of your input. A word is an unbroken set of
characters. Spaces and tabs separate words.
Following is a simple example of date command which displays current date and time:
$date
You can customize your command prompt using environment variable PS1 explained in
Environment tutorial.
Shell Types
In UNIX there are two major types of shells:
1. The Bourne shell. If you are using a Bourne-type shell, the default prompt is the $
character.
2. The C shell. If you are using a C-type shell, the default prompt is the % character.
There are again various subcategories for Bourne Shell which are listed as follows:
• Bourne shell ( sh)
• Korn shell ( ksh)
• Bourne Again shell ( bash)
• POSIX shell ( sh)
The different C-type shells follow:
• C shell ( csh)
• TENEX/TOPS C shell ( tcsh)
The original UNIX shell was written in the mid-1970s by Stephen R. Bourne while he
was at AT&T Bell Labs in New Jersey.
The Bourne shell was the first shell to appear on UNIX systems, thus it is referred to as
"the shell".
The Bourne shell is usually installed as /bin/sh on most versions of UNIX. For this
reason, it is the shell of choice for writing scripts to use on several different versions of
UNIX.
Shell Scripts
The basic concept of a shell script is a list of commands, which are listed in the order of
execution. A good shell script will have comments, preceded by a pound sign, #,
describing the steps.
There are conditional tests, such as value A is greater than value B, loops allowing us to
go through massive amounts of data, files to read and store data, and variables to read and
store data, and the script may include functions.
Shell scripts and functions are both interpreted. This means they are not compiled.
We are going to write a many scripts in the next several tutorials. This would be a simple
text file in which we would put our all the commands and several other required
constructs that tell the shell environment what to do and when to do it.
Example Script
Assume we create a test.sh script. Note all the scripts would have .sh extension. Before
you add anything else to your script, you need to alert the system that a shell script is
being started. This is done using the shebang construct. For example:
#!/bin/sh
This tells the system that the commands that follow are to be executed by the Bourne
shell. It's called a shebang because the # symbol is called a hash, and the ! symbol is
called a bang.
To create a script containing these commands, you put the shebang line first and then add
the commands:
#!/bin/bash
ls –l
mkdir teji
UNIX/Linux Variables
Variables are a way of passing information from the shell to programs when you run
them. Programs look "in the environment" for particular variables and if they are found
will use the values stored. Some are set by the system, others by you, yet others by the
shell, or any program that loads another program.
Standard UNIX variables are split into two categories, environment variables and shell
variables. In broad terms, shell variables apply only to the current instance of the shell
and are used to set short-term working conditions; environment variables have a farther
reaching significance, and those set at login are valid for the duration of the session. By
convention, environment variables have UPPER CASE and shell variables have lower
case names. It is used to store data and configuration options. Two type of variables.
System variables: Created and maintained by Linux bash shell. system variables are
defined in CAPITAL LETTERS. You can configure aspects of the shell by modifying
system variables such as PS1, PATH, LANG, HISTSIZE, and DISPLAY etc.
Example: To view all System Variables
Type the following command at terminal:
[root@localhost]#set
OR
[root@localhost]#env
OR
[root@localhost]#printenv
Variable Types:
When a shell is running, three main types of variables are present:
• Local Variables: A local variable is a variable that is present within the current
instance of the shell. It is not available to programs that are started by the shell.
They are set at command prompt.
• Environment Variables: An environment variable is a variable that is available
to any child process of the shell. Some programs need environment variables in
order to function correctly. Usually a shell script defines only those environment
variables that are needed by the programs that it runs.
• Shell Variables: A shell variable is a special variable that is set by the shell and is
required by the shell in order to function correctly. Some of these variables are
environment variables whereas others are local variables.
variable examples
The following examples are valid variable names:
_teji
var_a
VAR_1
Var_2
Following are the examples of invalid variable names:
3_val
-VAL
VAL1-VAL2
VAL_A!
The reason you cannot use other characters such as !,*, or - is that these characters have a
special meaning for the shell.
Defining Variables
Variables are defined as follows::
variable_name=variable_value
For example:
EMPNAME="POOJA SHARMA"
Above example defines the variable NAME and assigns it the value " POOJA SHARMA
". Variables of this type are called scalar variables. A scalar variable can hold only one
value at a time.
The shell enables you to store any value you want in a variable. For example:
VAL1="VIPUL GUPTA"
VAL2=500
Accessing Values
To access the value stored in a variable, prefix its name with the dollar sign ( $):
For example, following script would access the value of defined variable NAME and would print it on
STDOUT: #!/bin/sh
EMPNAME="POOJA SHARMA"
echo $EMPNAME
This would produce following value:
POOJA SHARMA
Read-only Variables
The shell provides a way to mark variables as read-only by using the readonly command.
After a variable is marked read-only, its value cannot be changed.
For example, following script would give error while trying to change the value of
NAME: #!/bin/sh
EMPNAME=" VIPUL GUPTA "
readonly NAME
EMPNAME="POOJA SHARMA"
This would produce following result:
/bin/sh: EMPNAME: This variable is read only.
Unsetting Variables
Unsetting or deleting a variable tells the shell to remove the variable from the list of
variables that it tracks. Once you unset a variable, you would not be able to access stored
value in the variable.
Following is the syntax to unset a defined variable using the unset command:
unset variable_name
Above command would unset the value of a defined variable. Here is a simple example:
#!/bin/sh
EMPNAME=" VIPUL GUPTA "
unset EMPNAME
EMPNAME="POOJA SHARMA"
echo $EMPNAME
Above example would not print anything. You cannot use the unset command to unset
variables that are marked readonly
Environment Variables
An example of an environment variable is the OSTYPE variable. The value of this is the
current operating system you are using. Type
% echo $OSTYPE
More examples of environment variables are
USER (your login name)
HOME (the path name of your home directory)
HOST (the name of the computer you are using)
ARCH (the architecture of the computers processor)
DISPLAY (the name of the computer screen to display X windows)
PRINTER (the default printer to send print jobs)
PATH (the directories the shell should search to find a command)
Finding out the current values of these variables.
ENVIRONMENT variables are set using the setenv command, displayed using the
printenv or env commands, and unset using the unsetenv command.
To show all values of these variables, type
% printenv | less
Shell Variables
An example of a shell variable is the history variable. The value of this is how many shell
commands to save, allow the user to scroll back through all the commands they have
previously entered. Type
% echo $history
More examples of shell variables are
cwd (your current working directory)
home (the path name of your home directory)
path (the directories the shell should search to find a command)
prompt (the text string used to prompt for interactive commands shell your login shell)
Finding out the current values of these variables.
SHELL variables are both set and displayed using the set command. They can be unset
by using the unset command.
To show all values of these variables, type
% set | less
So what is the difference between PATH and path?
In general, environment and shell variables that have the same name (apart from the case)
are distinct and independent, except for possibly having the same initial values. There
are, however, exceptions.
Each time the shell variables home, user and term are changed, the corresponding
environment variables HOME, USER and TERM receive the same values. However,
altering the environment variables has no effect on the corresponding shell variables.
PATH and path specify directories to search for commands and programs. Both variables
always represent the same directory list.
Commonly Used Shell Variables
System Variable Meaning
BASH_VERSION Holds the version of this instance of bash.
HOSTNAME The name of your computer.
CDPATH The search path for the cd command.
HISTFILE The name of the file in which command history is saved.
HISTFILESIZE The maximum number of lines contained in the history file.
HISTSIZE The number of commands to remember in the command history.
The default value is 500.
HOME The home directory of the current user.
The Internal Field Separator that is used for word splitting after
IFS expansion and to split lines into words with the read builtin
command. The default value is <space><tab><newline>.
Used to determine the locale category for any category not
LANG
specifically selected with a variable starting with LC_.
The search path for commands. It is a colon-separated list of
PATH
directories in which the shell looks for commands.
PS1 Your prompt settings.
The default timeout for the read builtin command. Alsom in an
interactive shell, the value is interpreted as the number of seconds to
TMOUT
wait for input after issuing the command. If not input provided it
will logout user.
TERM Your login terminal type.
SHELL Set path to login shell.
DISPLAY Set X display name
EDITOR Set name of default text editor.
Shell comments
Single line comments A word or line beginning with # causes that word and all
remaining characters on that line to be ignored is known as comments.These lines aren't
executeable and shell simply ignores them.Comments makes source code easier to
understand and used as help for users and other sys admins.It provides help for sys
admins to understand code, logic and support to modify the script.
Example:#!/bin/bash
#This is my first shell script
During exection all the lines containing # in beginging will be treated as comments and
are’t excutable.
Multiple line comments when a detailed help or comments more than one line is reqired
than it is better to use multiple line comments.
Example:
<<COMMENT1
This shell script is used to add and delete users.
Also provide support to set various other properties.
For more information login to www.nutansolution.com
COMMENT1
test
Command test is a built-in command. The test command evaluate an expression and
Returns a condition code indicating that the expression is either true (0) or false (not
0)Argument.
Syntax: test expression
Expression criteria:
Logical AND operator to separate two criteria: -a
Logical OR operator to separate two criteria: -o
Negate any criterion: !
Group criteria with parentheses
Separate each element with a SPACE
Test Criteria
Shell Special Variables
Variable Description
$0 The filename of the current script.
These variables correspond to the arguments with which a script was
invoked. Here n is a positive decimal number corresponding to the position
$n
of an argument (the first argument is $1, the second argument is $2, and so
on).
$# The number of arguments supplied to a script.
All the arguments are double quoted. If a script receives two arguments, $*
$*
is equivalent to $1 $2.
All the arguments are individually double quoted. If a script receives two
$@
arguments, $@ is equivalent to $1 $2.
$? The exit status of the last command executed.
$$ The process number of the current shell. For shell scripts, this is the process
ID under which they are executing.
$! The process number of the last background command.
Shell Operators
Arithmetic Operators
Supoose for examples used in table variable x holds 5 and variable y holds 10
Operator Description Example
Addition - Adds values on either side of
+ `expr $x + $y` will give 15
the operator
Subtraction - Subtracts right hand operand
- `expr $x - $y` will give -5
from left hand operand
Multiplication - Multiplies values on
* `expr $x * $y` will give 150
either side of the operator
Division - Divides left hand operand by
/ `expr $y / $x` will give 2
right hand operand
Modulus - Divides left hand operand by
% `expr $y % $x` will give 0
right hand operand and returns remainder
Assignment - Assign right operand in left z=$y would assign value of y
=
operand into z
Equality - Compares two numbers, if both
== [ $x == $y ] would return false.
are same then returns true.
Not Equality - Compares two numbers, if
!= [ $x != $y ] would return true.
both are different then returns true.
Relational Operators
Supoose for examples used in table variable x holds 5 and variable y holds 10
Operator Description Example
Checks if the value of two operands is
-eq equal or not, if yes then condition [ $x -eq $y ] is false.
becomes true.
Checks if the value of two operands are
-ne equal or not, if values are not equal then [ $x -ne $y ] is true.
condition becomes true.
Checks if the value of left operand is
-gt greater than the value of right operand, if [ $x -gt $y ] is false.
yes then condition becomes true.
Checks if the value of left operand is less
-lt than the value of right operand, if yes then [ $x -lt $y ] is true.
condition becomes true.
Checks if the value of left operand is
greater than or equal to the value of right
-ge [ $x -ge $y ] is false.
operand, if yes then condition becomes
true.
Checks if the value of left operand is less
-le than or equal to the value of right operand, [ $x -le $y ] is true.
if yes then condition becomes true.
String Operators:
Supoose for examples used in table variable x holds “teji”and variable y holds “sema”
Operator Description Example
Checks if the value of two operands are
= equal or not, if yes then condition [ $x = $y ] is false.
becomes true.
Checks if the value of two operands are
!= equal or not, if values are not equal then [ $x != $y ] is true.
condition becomes true.
Checks if the given string operand size is
-z zero. If it is zero length then it returns [ -z $x ] is not true.
true.
Checks if the given string operand size is
-n non-zero. If it is non-zero length then it [ -z $x ] is not false.
returns true.
Boolean Operators
Supoose for examples used in table variable x holds 5 and variable y holds 10
Operator Description Example
This is logical negation. This inverts a
! [ ! false ] is true.
true condition into false and vice versa.
This is logical OR. If one of the operands
-o [ $x -lt 10 -o $y -gt 500 ] is true.
is true then condition would be true.
File Test Operators
Assume a variable fname holds an existing file name "check" whose size is 50 bytes and
has read, write and execute permissions.
Operator Description Example
Checks if file is a block special file if yes
-b file [-b $file] is false.
then condition becomes true.
Checks if file is a character special file if
-c file [-b $file] is false.
yes then condition becomes true.
Check if file is a directory if yes then
-d file [-d $file] is false.
condition becomes true.
Check if file is an ordinary file as opposed
-f file to a directory or special file if yes then [-f $file] is true.
condition becomes true.
Checks if file has its set group ID (SGID)
-g file [-g $file] is false.
bit set if yes then condition becomes true.
Checks if file has its sticky bit set if yes
-k file [-k $file] is false.
then condition becomes true.
Checks if file is a named pipe if yes then
-p file [-p $file] is false.
condition becomes true.
Checks if file descriptor is open and
-t file associated with a terminal if yes then [-t $file] is false.
condition becomes true.
Checks if file has its set user id (SUID) bit
-u file [-u $file] is false.
set if yes then condition becomes true.
Checks if file is readable if yes then
-r file [-r $file] is true.
condition becomes true.
Check if file is writable if yes then
-w file [-w $file ] is true.
condition becomes true.
Check if file is execute if yes then
-x file [-x $file] is true.
condition becomes true.
Check if file has size greater than 0 if yes
-s file [-s $file] is true.
then condition becomes true.
Check if file exists. Is true even if file is a
-e file [-e $file] is true.
directory but exists.
Shell Decision Making
Syntax
if [ expression ]
then
Statement(s) to be executed if expression is true
fi
Example1
[root@localhost Shell]# vi wordmatch.sh
if test “$word1” = “$word2” then
echo “Match”
fi
Example2
[root@localhost Shell]# vi test.sh
if test $# -eq 0
then
echo “ you must supply at least one arguments”
exit 1
fi
Example1:
#!/bin/bash
echo -p "Enter a password"
read password
if test "$password" = "teji"
then
echo "Password verified."
else
echo "Access denied."
fi
Example2:
#!/bin/bash
echo -ne "Enter number : "
read num
if test $num -ge 0
then
echo "$num is positive number."
else
echo "$num number is negative number."
fi
Example:
#!/bin/bash
echo –ne "Enter a number := "
read num
if [ $num -gt 0 ] then
echo "$num is a positive."
elif [ $num -lt 0 ]
then
echo "$num is a negative."
elif [ $num -eq 0 ]
then
echo "$num is zero number."
else
echo " $num is not a number."
fi
Example:
#!/bin/sh
echo “\n Command MENU\n”
echo “ a. Current data and time”
echo “ b. Users currently logged in”
echo “ c. Name of the working directory\n”
echo “Enter a,b, or c: \c”
read choice
echo
case “$choice” in
a)
date
;;
b)
who
;;
c)
pwd
;;
*)
echo “There is no selection: $choice”
;;
esac
Example:
#!/bin/sh
a=1
while [ $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
Output:
1
2
3
4
5
6
7
8
9
10
The for… in loop
Syntax:
for loop-index in argument_list
do
commands
done
Example:
for file in *
do
if [ -d “$file” ]; then
echo $file
fi
done
Example:
secretname=jenny
name=noname
until [ “$name” = “$secretname” ]
do
echo “ Your guess: \c”
read name
done
Example:
#!/bin/sh
a=0
until [ ! $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
Example:
#!/bin/sh
select COLOR in red blue pink white green all none
do
case $ COLOR in
red|pink|white|all)
echo "Good choice"
;;
blue|green)
echo "bad choice"
;;
none)
break
;;
*) echo "wrong choice ,Try again!!!!"
;;
esac
done
Shell Loop Control
break and continue
Interrupt for, while or until loop
The break statement:Transfer control to the statement AFTER the done statement and
Terminate execution of the loop.
The continue statement:Transfer control to the statement to the done statement and
Skip the test statements for the current iteration Continues execution of the loop.
Example:
for index in 1 2 3 4 5 6 7 8 9 10
do
if [ $index –le 3 ] then
echo “continue”
continue
fi
echo $index
if [ $index –ge 8 ] then
echo “break”
break
fi
done
Example:
#!/bin/sh
NUMS="1 2 3 4 5 6 7"
for NUM in $NUMS
do
Q=`expr $NUM % 2`
if [ $Q -eq 0 ]
then
echo "Number is an even number!!"
continue
fi
echo "Found odd number"
done
Example:
[root@localhost ~]# exec who
Redirect standard output, input or error of a shell script from within the script
exec < infile
exec > outfile 2> errfile
Example:
[root@localhost ~]# more redirect.sh
exec > /dev/tty
echo "this is a test of redirection"
[root@localhost ~]#./redirect.sh 1 > /dev/null 2 >& 1
This is a test of redirection
Functions
A shell function is similar to a shell script. It stores a series of commands for execution at
a later time. The shell stores functions in the memory. Shell executes a shell function in
the same shell that called it.
Where to define
In .profile
In your script
Or in command line
Remove a function
Use unset built-in
Syntax
function_name()
{
commands
}
Example:
[root@localhost ~]# whoson()
{
date
echo "users currently logged on"
who
}
[root@localhost ~]# whoson
Tue Feb 1 23:28:44 EST 2005
users currently logged on
teji :0 Jan 31 12:08
puneet pts/1 Jan 31 01:54 (:0.0)
pooja pts/2 Jan 31 05:02 (:0.0)
Example:-
[root@localhost~]#more .profile
setenv()
{
if [ $# -eq 2 ]
then
eval $1=$2
export $1
else
echo "usage: setenv NAME VALUE" 1>&2
fi
}
OUTPUT IS:
[root@localhost ~]# sh shell1.sh
Enter First Number=
12
Enter Second Number=
13
Addition is=
25
Subtraction is=
-1
Multiplication is=
156
Remainder is=
12
Quotient is=
0
2)#!/bin/sh
#shell script to perform floating arithmetic operations on two numbers
echo "Enter First Number="
read num1
echo "Enter Second Number="
read num2
echo "Addition is="
echo $num1 + $num2|bc
echo "Subtraction is="
echo $num1 - $num2|bc
echo "Multiplication is="
echo $num1 \* $num2|bc
echo "Remainder is="
echo $num1 % $num2|bc
echo "Quotient is="
echo $num1 / $num2|bc
OUTPUT IS:-
[root@localhost ~]# sh shell2.sh
Enter First Number=
12.5
Enter Second Number=
2.3
Addition is=
14.8
Subtraction is=
10.2
Multiplication is=
28.7
Remainder is=
1.0
Quotient is=
5
3) #!/bin/sh
#shell script to find the sum of digits of a given number
echo "enter number"
read a
i=10000
sum=0
while [ $i -ge 1 ]
do
sum=`expr $sum+$a/$i|bc`
a=`expr $a%$i|bc`
#new dividend=a previous remainder is new dividend
i=`expr $i/10|bc`
done
echo "sum=$sum"
4)#!/bin/sh
#shell script that displays all the links to a file specified as the first argument to the
#script. The second argument which is optional can be used to specify in which the
#search is to begin .If this second argument is not present, the search is to begin in
#current working directory. In either case the starting directory as well as all the
#subdirectories at all levels must be searched and the script need not check error
#massage.
touch rtemp
if [ $# -lt 1 ]
then
echo "no arguments"
else
s=`ls -l "$1" | tr -s " " | cut -d " " -f2`
if [ $s > 1 ]
then
echo "hard links are"
x=`ls -ilR $1 | cut -d " " -f1`
echo "inode=$x"
ls -ilR | grep "$x"
else
echo "no hard links"
fi
ls -ilR | grep "$1" > rtemp
z=`wc -l "rtemp"`
p=`echo "$z" | cut -d " " -f1`
if [ $p -gt 1 ]
then
echo "soft link are"
ls -ilR | grep "$1$"
else
echo "no soft link"
fi
fi
rm rtemp
Output1:
[root@localhost~]#sh links.sh
No arguments
Output2:
[root@localhost~]#sh links.sh rev.sh
Hard links are
233333 -rw-rw-r—2 teji teji 321 Apr 9 10:30 rev.sh
233333 –rw-rw-r—2 teji teji 321 Apr 9 10:30 test2
No soft links
5) #!/bin/sh
#shell script to merge one file to another and display the contents of #file
echo "enter filename 1="
read fname1
echo "enter second filename="
read fname2
echo "enter data= "
cat> $fname1
echo -ne "\n enter data="
cat >$fname2
echo -ne "\n enter filename3="
read fname3
echo -ne "\n after merging file3 is="
cat >>$fname1 $fname2
mv $fname1 $fname3
cat $fname3
OUTPUT :
[root@localhost ~]# sh merge.sh
enter filename 1=
text1.txt
enter second filename=
text2.txt
enter data=
hi all
how r u
enter data=
hi i am an Indian
what abt u
enter filename3=text3.txt
after merging file3 is=
hi all
how r u
hi i am an indian
what abt u
6)#!/bin/sh
# Shell script that accepts one or more file names as arguments and converts all of
them #to uppercase ,provided they exist in current directory.
if [ $# -lt 1 ]
then
echo "no arguments"
else
for i in $*
do
if [ ! -e $i ]
then
echo " File $i Does not exists"
else
x=`echo $1 | tr '[a-z]' '[A-Z]'`
echo $i ::: $x
fi
done
fi
Output:
[root@localhost~]#sh links.sh rev.sh ntfile.sh
links.sh
rev.sh
File ntfile.sh does not exist
7) #!/bin/sh
#shell script to find largest of three numbers
echo "Enter three numbers"
read a
read b
read c
if [ $a -gt $b ] && [ $a -gt $c ]
then
echo "first number is largest"
elif [ $b -gt $a ] && [ $b -gt $c ]
then
echo "second number is largest"
else
echo "third number is largest"
fi
Output:
[root@localhost ~]# sh large.sh
enter three numbers
20
10
2
First number is largest
8)#!/bin/sh
#Non recursive shell script which accept any number of argument and print them in
the #reverse order (ex:if the script is named rags then executing rags 1 2 3 4 should
produce # 4 3 2 1 on the standard output)
if [ $# -eq 0 ]
then
echo "no arguments"
else
for i in $*
do
echo $i >> temp
done
i=$#
while [ $i -ne 0 ]
do
head -$i temp | tail -1
i=`expr $i - 1`
done
fi
Output:
[root@localhost~]#sh rev.sh 1 2 3 4
4
3
2
1
9) #!/bin/sh
#shell script to find average of n numbers
echo "Enter the range of numbers"
read n
i=1
sum=0.0
avg=0.0
echo "enter the numbers"
while [ $i -le $n ]
do
read a
sum=`expr $sum+$a|bc`
i=`expr $i+1|bc`
done
avg=`expr $sum/$n|bc`
echo "the average of numbers is "
echo $avg
10) #!/bin/sh
#shell script which accepts valid login name as arguments and prints their
#corresponding home directories if no arguments are specified print a suitable error
#massage.
if [ $# -lt 1 ]
then
echo "no arguments"
else
for i in $*
do
x=`cat /etc/passwd | cut -d ":" -f6 | grep -w "$i"`
if [ -z $x ]
then
echo " no user of the name "$i
else
echo "Home directory of $i is "$x
fi
done
fi
Output1:
[root@localhost~]#sh homedir.sh teji
There is no user of the name teji
Output2:
[root@localhost~]#sh homedir.sh ram
The home directory of ram is /home/ran
11) #!/bin/sh
#shell script to find the factorial of a given number
echo "Enter the number"
read num
i=2
fact=1
while [ $i -le $num ]
do
fact=`expr $fact*$i|bc`
i=`expr $i+1|bc`
done
echo "The factorial of the number is:"
echo $fact
Output:
[root@localhost ~]# sh fact.sh
Enter the number
5
The factorial of the number is:
120
12) #!/bin/sh
#shell script to perform following file operations copy, edit, rename, remove a file
while true
do
echo -ne "\n\n\t********MENU**********
1.COPY
2.EDIT
3.RENAME
4.REMOVE
5.EXIT"
echo -ne "\n Enter Your Choice="
read choice
case $choice in
1)echo "Enter source filename="
read sname
echo "Enter data and press ^d"
cat >$sname
echo "Enter target filename="
read tname
cp $sname $tname
echo "After copying target file is= "
cat $tname
;;
2)echo "Enter source filename="
read sname
echo "Enter data and press ^d"
cat >$sname
vi $sname
echo "After editing source file is= "
cat $sname
;;
OUTPUT is:-
[root@localhost ~]# sh fileo.sh
********MENU**********
1.COPY
2.EDIT
3.RENAME
4.REMOVE
5.EXIT
Enter Your Choice=1
Enter source filename=
text1.txt
Enter data and press ^d
hi how r u
i m an indian
east or west india is best
Enter target filename=
text2.txt
After copying target file is=
hi how r u
i m an indian
east or west india is best
********MENU**********
1.COPY
2.EDIT
3.RENAME
4.REMOVE
5.EXIT
Enter Your Choice=2
Enter source filename=
text1.txt
Enter data and press ^d
hi i m an indian
wht abt u
After editing source file is=
hi i m an indian
wht abt u
east or west india is the best
i m proud to be an indian
********MENU**********
1.COPY
2.EDIT
3.RENAME
4.MOVE
5.REMOVE
6.EXIT
Enter Your Choice=3
Enter source filename=
text1.txt
Enter data and press ^d
hi i m an indian
what abt u
Enter target filename=
text2.txt
After rename target file is=
hi i m an indian
what abt u
After rename source file is=
cat: text1.txt: No such file or directory
********MENU**********
1.COPY
2.EDIT
3.RENAME
4.REMOVE
5.EXIT
Enter Your Choice=4
Enter source filename=
text1.txt
Enter data and press ^d
hi all
linux operating system
After deletion message is=
cat: text1.txt: No such file or directory
********MENU**********
1.COPY
2.EDIT
3.RENAME
4.REMOVE
5.EXIT
Enter Your Choice=k
INVALID CHOICE
********MENU**********
1.COPY
2.EDIT
3.RENAME
4.REMOVE
5.EXIT
Enter Your Choice=5
[root@localhost ~]#
13)#!/bin/sh
#shell script that accept two filenames as arguments checks if the permissions are
#identical and if the permissions are identical ,output common permissions otherwise
#output each filename followed by its permissions.
if [ $# -lt 1 -o $# -gt 2 ]
then
echo " arguments are not valid "
else
if [ -e $1 -a -e $2 ]
then
x=`ls -l $1 | cut -d " " -f 1`
y=`ls -l $2 | cut -d " " -f 1`
if [ $x == $y ]
then
echo " permission of $1 and $2 are equal"
echo " common permissions: $x"
else
echo " Permissions are not same"
echo "$1 has : $x "
echo "$2 has : $y "
fi
else
echo " file does not exists"
fi
fi
output1:
[root@localhost~]#sh ram.sh
arguments are not valid
output2:
[root@localhost~]#sh links.sh rev.sh
Permissions of links.sh and rev.sh are equal.
Common permission is : -rw-r--r--
Output3:
[root@localhost~]#sh fileo.sh links.sh
Permission are not same
fileo.sh has: -rw-r-xrwx
links.sh has: -rw-r--r--
14) #!/bin/sh
#shell script to generate the Fibonacci series
echo "Enter the number of terms in the Fibonacci series"
read n
s=0
a=1
b=1
echo "The Series is :"
echo $s
echo $a
echo $b
s=`expr $a+$b|bc`
echo $s
n=`expr $n-3|bc`
while [ $n -gt 0 ]
do
a=$b
b=$s
s=`expr $a+$b|bc`
echo $s
n=`expr $n-1|bc`
done
Output:
[root@localhost Shell]# sh fibno.sh
Enter the number of terms in the fibonacci series
6
The Series is :
0
1
1
2
3
5
15)#!/bin/sh
#shell script that accepts a path name and creates all the components in the path name
#as directories (ex:teji/seema/nonu/ram should creates a directory teji, teji/seema,
teji/seema/nonu, teji/seema/nonu/ram)
if [ $# -lt 1 ]
then
echo " no arguments"
else
echo $1 | tr "/" " " > temp
for i in $temp
do
mkdir $i
cd $i
done
echo "Directories are created"
fi
Output
[root@localhost~]#sh dircreat.sh teji/seema/nonu/ram
Directories are created.
16) #!/bin/sh
#shell script to design a menu driven calculator
while true
do
echo -ne "\n\n\t********MENU**********
1.ADDITION
2.SUBTRACTION
3.MULTIPLICATION
4.REMAINDER
5.QUOTIENT
6.EXIT"
echo -ne "\n Enter Your Choice="
read choice
case $choice in
1)echo "Enter first Number="
read num1
echo "Enter Second Number="
read num2
echo "Addition is= "
echo $num1 + $num2|bc
;;
2)echo "Enter first Number="
read num1
echo "Enter Second Number="
read num2
echo "Subtraction is= "
echo $num1 - $num2|bc
;;
3)echo "Enter first Number="
read num1
echo "Enter Second Number="
read num2
echo "Multiplication is= "
echo $num1 \* $num2|bc
;;
4)echo "Enter first Number="
read num1
echo "Enter Second Number="
read num2
echo "Remainder is= "
echo $num1 % $num2|bc
;;
5)echo "Enter first Number="
read num1
echo "Enter Second Number="
read num2
echo "Quotient is= "
echo $num1 / $num2|bc
;;
6)exit
;;
*)echo "INVALID CHOICE"
;;
esac
done
OUTPUT IS:-
[root@localhost ~]# sh calculator.sh
********MENU**********
1.ADDITION
2.SUBTRACTION
3.MULTIPLICATION
4.REMAINDER
5.QUOTIENT
6.EXIT
Enter Your Choice=1
Enter first Number=
12.4
Enter Second Number=
3.6
Addition is=
16.0
********MENU**********
1.ADDITION
2.SUBTRACTION
3.MULTIPLICATION
4.REMAINDER
5.QUOTIENT
6.EXIT
Enter Your Choice=2
Enter first Number=
12.8
Enter Second Number=
6.7
Subtraction is=
6.1
********MENU**********
1.ADDITION
2.SUBTRACTION
3.MULTIPLICATION
4.REMAINDER
5.QUOTIENT
6.EXIT
Enter Your Choice=3
Enter first Number=
12.9
Enter Second Number=
5.8
Multiplication is=
74.8
********MENU**********
1.ADDITION
2.SUBTRACTION
3.MULTIPLICATION
4.REMAINDER
5.QUOTIENT
6.EXIT
Enter Your Choice=4
Enter first Number=
45.7
Enter Second Number=
3.6
Remainder is=
2.5
********MENU**********
1.ADDITION
2.SUBTRACTION
3.MULTIPLICATION
4.REMAINDER
5.QUOTIENT
6.EXIT
Enter Your Choice=5
Enter first Number=
37.9
Enter Second Number=
23.5
Quotient is=
1
********MENU**********
1.ADDITION
2.SUBTRACTION
3.MULTIPLICATION
4.REMAINDER
5.QUOTIENT
6.EXIT
Enter Your Choice=9
INVALID CHOICE
********MENU**********
1.ADDITION
2.SUBTRACTION
3.MULTIPLICATION
4.REMAINDER
5.QUOTIENT
6.EXIT
17)#!/bin/sh
#shell script that takes a valid directory name as an argument and recursively descend
#all the subdirectories find its maximum length of any file in that hierarchy and writes
#this maximum value to the second output.
if [ $# -lt 1 ]
then
echo "arguments are not valid"
else
if [ -d $1 ]
then
ls -lR $1 | tr -s " " | sort -t " " -n -r -k 5 | grep "^[^d]" | head -1 |
cut -d " " -f 5,9
else
echo " Directory does not exist"
fi
fi
Output1:
[root@localhost~]#sh dirchk.sh ram
Directory does not exist
Output2:
[root@localhost~]#sh dirchk.sh teji
983 teji
18) #!/bin/sh
#shell script to search a word from a file
until false
do
echo "Enter filename="
read fname
echo "enter data and press ^d"
cat >$fname
echo "Enter word to be searched="
read word
grep $word $fname
if test -z "$word"
then
echo "word not found try other"
continue
fi
echo "given word is =$word"
break
done
19) #!/bin/sh
#Menu driven shell script to listing files, present working directory ,process running,
#display current system date
choice=y
while test choice=y
do
echo -e "\t\t****MENU*****
l.listing files
p. Present working directory
ps.process running
d.display current system date
e.exit"
echo -e "\n enter ur choice="
read option
case $option in
l)
echo "enter path="
read path
echo "contents is="
ls -al $path
;;
p)echo "present working directory is="
pwd
;;
ps)ps
;;
d)date
;;
e)exit
;;
*) echo "WRONG CHOICE!!!!!"
esac
done
OUTPUT IS:-
[root@localhost ~]# sh comand.sh
****MENU*****
l.listing files
p.presnt working directory
ps.process running
d.display current system date
e.exit
enter ur choice=
l
enter path=
/bin
contents is=
total 6796
drwxr-xr-x 2 root root 4096 Oct 23 00:26 .
drwxr-xr-x 23 root root 4096 Oct 23 05:38 ..
-rwxr-xr-x 1 root root 4760 May 4 2005 arch
lrwxrwxrwx 1 root root 4 Aug 27 16:58 awk -> gawk
-rwxr-xr-x 1 root root 17248 May 25 2005 basename
-rwxr-xr-x 1 root root 686520 May 10 2005 bash
-rwxr-xr-x 1 root root 21104 May 25 2005 cat
-rwxr-xr-x 1 root root 38828 May 25 2005 chgrp
-rwxr-xr-x 1 root root 38464 May 25 2005 chmod
-rwxr-xr-x 1 root root 41852 May 25 2005 chown
-rwxr-xr-x 1 root root 63256 May 25 2005 cp
-rwxr-xr-x 1 root root 103888 May 17 2005 cpio
lrwxrwxrwx 1 root root 4 Aug 27 17:00 csh -> tcsh
-rwxr-xr-x 1 root root 32312 May 25 2005 cut
-rwxr-xr-x 1 root root 47684 May 25 2005 date
-rwxr-xr-x 1 root root 34540 May 25 2005 dd
-rwxr-xr-x 1 root root 38696 May 25 2005 df
-rwxr-xr-x 3 root root 61424 May 3 2005 zcat
-rwxr-xr-x 1 root root 459884 Jan 17 2005 zsh
****MENU*****
l.listing files
p.presnt working directory
ps.process running
d.display current system date
e.exit
enter ur choice=
p
present working directory is=
/root
****MENU*****
l.listing files
p.presnt working directory
ps.process running
d.display current system date
e.exit
enter ur choice=
ps
PID TTY TIME CMD
4703 pts/1 00:00:00 bash
5372 pts/1 00:00:00 sh
5376 pts/1 00:00:00 ps
****MENU*****
l.listing files
p.presnt working directory
ps.process running
d.display current system date
e.exit
enter ur choice=
d
Mon Oct 23 09:03:34 IST 2006
****MENU*****
l.listing files
p.presnt working directory
ps.process running
d.display current system date
e.exit
enter ur choice=
m
WRONG CHOICE!!!!!
****MENU*****
l.listing files
p.presnt working directory
ps.process running
d.display current system date
e.exit
enter ur choice=
e
[root@localhost ~]#
20)#!/bin/sh
#shell script that reports the logging in of a specified user within one minute after
#he/she login. The script automatically terminate if specified user does not log in
#during a specified period of time.
echo “ enter the login name of the user “
read name
period=0
until who| grep –w”$name 2> /dev/null /* search for the user error are send to special
file */
do
sleep 60
period=`expr $period + 1`
if [ $period –gt 1 ]
then
echo “ $name has not login since 1 minute “
exit
fi
done
echo “ $name is now logged in “
Output1:
[root@localhost~]#sh login.sh
Enter the login name of the user
teji
teji is now logged in
21) #!/bin/sh
#shell script to copy one file to another and display the contents
echo "Enter source filename ="
read source
echo "Enter data and press ^d"
cat >$source
echo -e "\n Enter target file name="
read target
if cp $source $target
then
echo "file copied successfully"
echo "contents of target file is="
cat $target
else
echo "Failed to copied the file"
fi
output is:-
[root@localhost ~]# sh cp.sh
Enter source filename =
test.txt
Enter data and press ^d
linux programming
shell programming
c programing
Enter target file name=
tested.txt
file copied successfully
contents of target file is=
linux programming
shell programming
c programing
22)#!/bin/sh
#shell script that accepts two integers as its argument and compute the value of first
#number raised to the power of second number.
if [ $# -eq 0 ]
then
echo “not sufficient arguments”
else
x=$1
y=$2
if [ $y –eq 0 ]
then
mul=1
else
mul=1
I=1
if [ $y –le 0 ]
# if the power is less than 0 then this operation can be done
then
y=`expr $y \* -1
while [ $i –le $y ]
do
mul=`expr mul \* $x`
i=`expr $i + 1`
done
echo “the $x to the power $y is=1/mul”
else
while [ $i -le $y ]
do
mul=`expr $mul \* $x`
i=`expr $i + 1`
done
echo “the $x to the power of $y= $mul”
fi
fi
fi
Output:
[root@localhost~]#sh pow.sh 2 4
2 raised to the power of 4 is 16
23) #!/bin/sh
#Menu driven shell script to generate the students DMC
echo "Enter student name="
read sname
echo "Enter Fname="
read fname
echo "Enter student roll no="
read rollno
echo "Enter university registration no="
read uregno
echo "Enter address="
read address
echo "Enter marks in Linux="
read lin
echo "Enter marks in BBC="
read bbc
echo "Enter marks in Ecomerce="
read ec
echo "Enter marks in AI="
read ai
echo "Enter marks in CD="
read cd
sum=`expr $lin + $bbc + $ec + $ai + $cd`
avg=`expr $sum / 5`
OUTPUT1:
[root@localhost ~]# sh dmc.sh
Enter student name=
ram kumar
Enter Fname=
sh. jai kumar
Enter student roll no=
1203501
Enter university registration no=
96 gny 219
Enter address=
#213 ,KKR
Enter marks in Linux=
56
Enter marks in BBC=
67
Enter marks in Ecomerce=
77
Enter marks in AI=
77
Enter marks in CD=
66
OUTPUT2:
[root@localhost ~]# sh dmc.sh
Enter student name=
ram kumar
Enter Fname=
sh. jai kumar
Enter student roll no=
123
Enter university registration no=
96 gny 219
Enter address=
#213 KKR
Enter marks in Linux=
56
Enter marks in BBC=
45
Enter marks in Ecomerce=
66
Enter marks in AI=
58
Enter marks in CD=
72
OUTPUT3:
[root@localhost ~]# sh dmc.sh
Enter student name=
ram kumar
Enter Fname=
sh. jai kumar
Enter student roll no=
1203501
Enter university registration no=
96 gny 219
Enter address=
#213 KKR
Enter marks in Linux=
47
Enter marks in BBC=
45
Enter marks in Ecomerce=
56
Enter marks in AI=
36
Enter marks in CD=
55
*******DETAILED MARK CARD**********
Student Name :=ram kumar
student Father Name :=sh. jai kumar
Student Roll NO :=1203501
University Registration NO :=ram kumar
Student Address :=#213 KKR
Student ram kumar result is :=THIRD DIVISION
OUTPUT4:
[root@localhost ~]# sh dmc.sh
Enter student name=
ram kumar
Enter Fname=
sh. jai kumar
Enter student roll no=
1203501
Enter university registration no=
96 gny 219
Enter address=
#213 KKR
Enter marks in Linux=
34
Enter marks in BBC=
20
Enter marks in Ecomerce=
56
Enter marks in AI=
36
Enter marks in CD=
23
24) #!/bin/sh
#shell script to generate electricity bill
echo "Enter Customer Bill Account Number="
read custno
echo "Enter Customer Name="
read custname
echo "Enter Customer Address="
read custadd
echo "Enter Previous Reading="
read pread
echo "Enter Current Reading="
read cread
consunits=`expr $cread - $pread`
if test $consunits -le 100
then
bill1=$consunits
elif test $consunits -gt 100 -a $consunits -le 200
then
unitrem=`expr $consunits - 100`
bill=`expr $unitsrem \* 2`
bill1=`expr $bill + 100`
elif test $consunits -gt 200
then
unitsrem=`expr $consunits - 200`
bill=`expr $unitrem \* 3`
bill1=`expr $bill + 300`
fi
dbill=`expr $bill1 + 20`
echo $dbill
echo -ne "\n\n******************ELECTRICITY BILL******************"
echo -ne "\nCUSTOMER NAME :=$custname"
echo -ne "\nCUSTOMER ACCOUNT NUMBER :=$custno"
echo -ne "\nCUSTOMER ADDRESS :=$custadd"
echo -ne "\nPREAVIOUS READING :=$pread"
echo -ne "\nCURRENT READING :=$cread"
echo -ne "\nUNITS CONSUMED :=$consunits"
echo -ne "\nBILL PAYED(ON DATE) :=$bill1"
echo -ne "\nBILL PAYED(AFTER DATE) :=$dbill"
Output1:
[root@localhost ~]# sh bill.sh
Enter Customer Bill Account Number=
1234
Enter Customer Name=
Ram Kumar
Enter Customer Address=
#1232 ,KKR
Enter Previous Reading=
100
Enter Current Reading=
196
******************ELECTRICITY BILL******************
CUSTOMER NAME :=Ram Kumar
CUSTOMER ACCOUNT NUMBER :=1234
CUSTOMER ADDRESS :=#1232 ,KKR
PREAVIOUS READING :=100
CURRENT READING :=196
UNITS CONSUMED :=96
BILL PAYED(ON DATE) :=96
BILL PAYED(AFTER DATE) :=116
Output2:
[root@localhost ~]# sh bill.sh
Enter Customer Bill Account Number=
1234
Enter Customer Name=
Ram Kumar
Enter Customer Address=
#1232 ,KKr
Enter Previous Reading=
100
Enter Current Reading=
296
312
******************ELECTRICITY BILL******************
CUSTOMER NAME :=Ram Kumar
CUSTOMER ACCOUNT NUMBER :=1234
CUSTOMER ADDRESS :=#1232 ,KKr
PREAVIOUS READING :=100
CURRENT READING :=296
UNITS CONSUMED :=196
BILL PAYED(ON DATE) :=292
BILL PAYED(AFTER DATE) :=312
Output3:
[root@localhost ~]# sh bill.sh
Enter Customer Bill Account Number=
1234
Enter Customer Name=
Ram Kumar
Enter Customer Address=
#1232,KKR
Enter Previous Reading=
100
Enter Current Reading=
478
854
******************ELECTRICITY BILL******************
CUSTOMER NAME :=Ram Kumar
CUSTOMER ACCOUNT NUMBER :=1234
CUSTOMER ADDRESS :=#1232,KKR
PREAVIOUS READING :=100
CURRENT READING :=478
UNITS CONSUMED :=378
BILL PAYED(ON DATE) :=834
BILL PAYED(AFTER DATE) :=854
25)#!/bin/sh
#shell script to implement terminal locking (similar to the lock command) .it should
#prompt the user for the password .after accepting the password entered by the user it
#must prompt again for the matching password as confirmation and if match occurs it
#must lock the keyword until a matching password is entered again by the user ,note
#that the script must be written to disregard BREAK,control-D. No time limit need be
#implemented for the lock duration.
echo "terminal locking script"
echo "enter a password"
stty -echo
read password1
stty -echo
echo "re-enter the password"
stty -echo
read password2
stty echo
if [ $password1!=$password2 ]
echo "mismatch in password"
echo "terminal cannot be locked"
exit
fi
echo "terminal locked"
stty intr ^-
stty quit ^-
stty kill ^-
stty eof ^-
stty stop ^-
stty susp ^-
echo "Enter the password to unlock the terminal"
stty -echo
read password3
if [ $password3!=$passowrd1 ]
then
stty echo
echo "incorrect password"
fi
while [ $password3!=$passowrd1 ]
do
echo "Enter the password to unlock the terminal"
stty -echo
read password3
if [ $password3!=$passowrd1 ]
then
stty echo
echo "incorrect password"
fi
done
stty echo
stty sane
Output1 :
[root@localhost~]#sh passchk.sh
enter a password
re-enter the password
mismatch in password
terminal cannot be locked
Output2:
[root@localhost~]#sh passchk.sh
enter a password
re-enter the password
Terminal locked
26) #!/bin/sh
#Menu driven shell script to search a word from a given sentence
while true
do
echo -ne "\n\n\t********MENU**********
1.Enter sentence
2.search a given word
3.exit"
echo -ne "\n Enter Your Choice="
read choice
case $choice in
1)echo "Enter file name="
read fname
echo "Enter data and press ^d = "
cat >$fname
;;
2)echo "Enter file Name="
read fname
echo "Enter word to be searched="
read word
echo "Result After searching="
grep $word $fname || echo "word not found"
;;
3)exit
;;
*)echo "INVALID CHOICE"
;;
esac
done
OUTPUT IS:-
[root@localhost ~]# sh search.sh
********MENU**********
1.Enter sentence
2.search a given word
3.exit
Enter Your Choice=1
Enter file name=
test.txt
Enter data and press ^d =
hi i m an indian
india is a great country
india is best
hello world
hi all
********MENU**********
1.Enter sentence
2.search a given word
3.exit
Enter Your Choice=2
Enter file Name=
test.txt
Enter word to be searched=
india
Result After searching=
hi i m an indian
india is a great country
india is best
********MENU**********
1.Enter sentence
2.search a given word
3.exit
Enter Your Choice=2
Enter file Name=
test.txt
Enter word to be searched=
delhi
Result After searching=
word not found
********MENU**********
1.Enter sentence
2.search a given word
3.exit
Enter Your Choice=y
INVALID CHOICE
********MENU**********
1.Enter sentence
2.search a given word
3.exit
Enter Your Choice=3
27)#!/bin/sh
#Create a script file called file properties that reads a file name entered and output its
#properties.
echo “enter filename”
read file
c=1
if [ -e $file ] #checks the existence of the file
then
for i in `ls –l $file | tr –s “ “`
# ‘tr –s “ “’ treats 2 or more spaces as a single space
do
case “$c” in #case condition starts
1) echo “file permission=” $i ;;
2) echo “No of link =” $i;;
3) echo “file belongs to owner =” $i;;
4) echo “file belongs togroup=”$i ;;
5) echo “file size=” $i ;;
6) echo “file created in the month of=” $i ;;
7) echo “file creation date=” $i ;;
8) echo “last modification time=” $i ;;
9) echo “file name=” $i ;;
esac #end of case condition
c=`expr $c + 1`
done
else
echo “file does not exist”
fi
Output:
[root@localhost~]#sh filepermis.sh
enter filename
teji.sh
file permission=-rw-r- -r- -
link=1
file belongs to owner=teji
file belongs to group=teji
file size =555
file created in the month of =march
file creation date=12
last modification time=12:16
file name=teji.sh
28)#!/bin/sh
#shell script that accepts a list of file names as its argument, count and report
#occurrence of each word that is present in the first argument file on other argument
#file.
if [ $# -eq 0 ]
then
echo "no arguments"
else
tr " " "\n" < $1 > temp
shift
for i in $*
do
tr " " "\n" < $i > temp1
y=`wc -l < temp`
j=1
while [ $j -le $y ]
do
x=`head -n $j temp | tail -1`
c=`grep -c "$x" temp1`
echo $x $c
j=`expr $j + 1`
done
done
fi
29) #!/bin/sh
#shell script to sort numbers
echo "Enter source filename="
read fname
echo -ne "\nEnter Numeric data and press ^d\n"
cat >$fname
sort -g $fname >sortedfile
echo -e "\nUnsorted file is=\n"
cat $fname
echo -ne "\nSorted file is=\n"
cat sortedfile
OUTPUT IS:-
[root@localhost ~]# sh numsort.sh
Enter source filename=
number.txt
Enter Numeric data and press ^d
123
233
12
78
345
674
234
884
11
88
33
Unsorted file is=
123
233
12
78
345
674
234
884
11
88
33
Sorted file is=
11
12
33
78
88
123
233
234
345
674
884
30)#!/bin/sh
#shell script that delete all lines containing a specific word in one or more file supplied
#as argument to it.
if [ $# -eq 0 ]
then
echo "no arguments"
else
echo "enter a deleting word or char"
read y
for i in $*
do
grep -v "$y" "$i" > temp
if [ $? -ne 0 ]
then
echo "pattern not found"
else
cp temp $i
rm temp
fi
done
fi
31) #!/bin/sh
#shell script to search a word from a file
echo "Enter file name="
read fname
echo "Enter data and press ^d = "
cat >$fname
echo -e "\nEnter word to be searched="
read word
echo "Result After searching="
grep $word $fname || echo "word not found"
OUTPUT:
[root@localhost ~]# sh search.sh
Enter file name=
test.txt
Enter data and press ^d =
hi all
hello world
hello how r u
say hello to all
Enter word to be searched=
hello
Result After searching=
hello world
hello how r u
say hello to all
32)#!/bin/sh
#shell script to compute the sum of numbers passed to it as argument on command line
#display the result .
if [ $# -lt 2 ] #check the number of argument
then
echo “enter minimum two argument”
else
sum=0
for i in $* #for loop starts
do
sum=`expr $sum + $i` #to find the sum
done # for loop ends
echo “sum of $* is =” $sum
fi
Output:
[root@localhost~]#sh sum.sh 12 14
sum of 12 1 4 is = 26
33)#!/bin/sh
#shell script that gets executed displays the message either “good morning” “good
afternoon” “good evening” depend upon time at which user logs in.
x=`who am i | tr -s " " | cut -d " " -f5`
#x=5
if [ $x -ge 05 -a $x -lt 12 ]
then
echo "good morning"
elif [ $x -ge 12 -a $x -lt 16 ]
then
echo "good afternoon"
elif [ $x -ge 16 -a $x -le 21 ]
then
echo "good evening"
fi
Output:
[root@localhost~]#sh wish.sh
good evening
34) #!/bin/sh
#shell script to sort the given list of names
echo "Enter source filename="
read fname
echo -ne "\nEnter data and press ^d\n"
cat >$fname
sort $fname >sortedfile
echo -e "\nUnsorted file is=\n"
cat $fname
echo -ne "\nSorted file is=\n"
cat sortedfile
OUTPUT :
[root@localhost ~]# sh sort.sh
Enter source filename=
name.txt
Enter data and press ^d
ramesh
ram kumar
parveen
amit
neha
richa
sivani
vikas
pooja
Unsorted file is=
ramesh
ram kumar
parveen
amit
neha
richa
sivani
vikas
pooja
Sorted file is=
amit
neha
parveen
pooja
ramesh
ram kumar
richa
sivani
vikas
35)#!/bin/sh
# shell script to display the calendar for current month with current date replaced by *
# or ** depending on whether the date has one digit or two.
n=`date +%d`
cal >temp
if [ $n -lt 10 ]
then
sed s/"$n"/*/g temp
else
sed s/"$n"/**/g temp
fi
36) #!/bin/sh
#Menu driven shell script to convert 1. LOWER TO UPPER
# 2. UPPER TO LOWER
# 3. CONVERT TAB INTO BLANK SPACE IN A FILE
until false
do
echo -e "\n\n\n\t *****MENU*******
1. LOWER TO UPPER
2. UPPER TO LOWER
3. CONVERT TAB INTO BLANK SPACE IN A FILE
4. EXIT"
echo -e "\nEnter ur choice="
read choice
case $choice in
1)
echo "Enter source filename="
read source
echo "Enter sentence in lowercase "
vi $source
echo "Enter target filename="
read target
dd if=$source of=$target conv=ucase
echo "contents of source file is="
cat $source
echo "Contents of target file after conversion="
cat $target
;;
2)
echo "Enter source filename="
read source
echo "Enter sentence in uppercase "
vi $source
4) exit
;;
*) echo "wrong choice"
esac
done
OUTPUT IS:-
[root@localhost ~]# sh stou.sh
*****MENU*******
1. LOWER TO UPPER
2. UPPER TO LOWER
3. CONVERT TAB INTO BLANK SPACE IN A FILE
4. EXIT
Enter ur choice=
1
Enter source filename=
text1.txt
Enter sentence in lowercase
Enter target filename=
text2.txt
contents of source file is=
hi i m an indian
who r u
what is ur name?
what abt others
0+1 records in
0+1 records out
Contents of target file after conversion=
HI I M AN INDIAN
WHO R U
WHAT IS UR NAME?
WHAT ABT OTHERS
*****MENU*******
1. LOWER TO UPPER
2. UPPER TO LOWER
3. CONVERT TAB INTO BLANK SPACE IN A FILE
4. EXIT
Enter ur choice=
2
Enter source filename=
text3.txt
Enter sentence in lowercase
Enter target filename=
text4.txt
contents of source file is=
INDIA IS A GREAT COUNTRY
INDIA IS BEST
0+1 records in
0+1 records out
Contents of target file after conversion=
india is a great country
india is best
*****MENU*******
1. LOWER TO UPPER
2. UPPER TO LOWER
3. CONVERT TAB INTO BLANK SPACE IN A FILE
4. EXIT
Enter ur choice=
3
Enter source filename=
test.txt
Enter tabed sentences
q u e s t i o n
a n s w e r
Contents of source file after conversion=
question
answer
*****MENU*******
1. LOWER TO UPPER
2. UPPER TO LOWER
3. CONVERT TAB INTO BLANK SPACE IN A FILE
4. EXIT
Enter ur choice=
k
wrong choice
*****MENU*******
1. LOWER TO UPPER
2. UPPER TO LOWER
3. CONVERT TAB INTO BLANK SPACE IN A FILE
4. EXIT
Enter ur choice=
4
37)#!/bin/sh
#Write a shell script that accepts as filename as argument and display its creation time
#if file exist and if it does not send output error massage.
if [ $# -eq 0 ]
then
echo "no arguments"
else
for i in $*
do
if [ ! -e $i ]
then
echo "file not exist"
else
ls -l $i | tr -s " " | cut -d " " -f7
fi
done
fi
Chapter 8
Basic Linux Administration
8.0 Basics of User and Group Administration
UID
This is an incremental number unique for every user and operating system uses it to
distinguished different users. UID for root is always 0. UID for normal user starts from
500. Maintenance/Service accounts use small number (typically less than 99).
GID
Identifies default group associated with user. The root group is always 0. Lower numbers
are used by system groups. Regular user numbers are listed in /etc/login.defs file.
Home directory:-This is where file and data of particular user resides.
Open /etc/login.defs in vi editor. It contains following information and we can edit this
information according to our requirement.
# Password aging controls:
# PASS_MAX_DAYS Maximum number of days a password may be used.
# PASS_MIN_DAYS Minimum number of days allowed between password changes.
# PASS_MIN_LEN Minimum acceptable password length.
# PASS_WARN_AGE Number of days warning given before a password expires.
PASS_MAX_DAYS 99999
PASS_MIN_DAYS 0
PASS_MIN_LEN 5
PASS_WARN_AGE 7
# Min/max values for automatic uid selection in useradd
UID_MIN 500
UID_MAX 60000
# Min/max values for automatic gid selection in groupadd
GID_MIN 500
GID_MAX 60000
Example: Adding a new user with user id 515 , belongs to group teji , having bash
shell ,account expires on 3/1/2007, and having name tajinder
[root@jmit ~]# adduser -u 515 -g teji -s /bin/bash -e 3/1/2007 tajinder
passwd command:-This command is used to set password for specified user.
syntax :- passwd username
[root@jmit ~]# passwd tajinder
Changing password for user tajinder.
New UNIX password:
BAD PASSWORD: it is based on a dictionary word
Retype new UNIX password:
passwd: all authentication tokens updated successfully.
NOTE: On 3rd January when you try to login with user name Tajinder the following
message will be displayed on your screen
Message is: Your session lasted only less than 10 seconds. If you have not logged out
yourself, this could be mean that there is some installation problem or that you may be out
of disk space .try logging in with failsafe session if you can fix this problem.
view details (~/.Xsession-errors file).
When a new user is created its entries are made in following two files
The /etc/passwd file contains basic user attributes. This is an ASCII file that
contains an entry for each user. Each entry defines the basic attributes applied to a user.
Another method of storing account information is with the shadow password
format. As with the traditional method, this method stores account information in the
/etc/passwd file in a compatible format. However, the password is stored as a single “x”
character (i.e. not actually stored as a single in this file). A second file, called
“/etc/shadow”, contains encrypted password as well as other information such as account
or password expiration values, etc. the /etc/shadow file is readable only by the root
account and is therefore less of a security risk.
[root@jmit ~]# vi /etc/passwd
tajinder:x:515:500::/home/tajinder:/bin/bash
Each field in a passwd entry is separated with “:” colon characters, and is as follows:
• Username up to 8 characters. Case-sensitive, usually all lowercase.
• An “X” in the password field. Passwords are stored in the “/etc/shadow” file.
• Numeric user id. This is assigned by the “adduser” script. UNIX uses this field,
plus the following group field, to identify which files belongs to the user.
• Numeric group id. Red Hat uses group id’s in a fairly unique manner for
enhanced file security. Usually the group id will match the user id.
• Full name user.
• User’s home directory. Usually /home /username (e.g./home /shah). All user’s
personal files, web pages, mail forwarding, etc. will be stored here.
• User’s “shell account “. Often set to /bin/ bash” to provide access to the bash shell
(my personal favorite shell).
After executing this command the shadow file is empty and doesn't contain any data. It is
not recommended to use this command. But if it is done to recover from it we use
following command
[root@jmit ~]# pwconv
Example: Adding a new user with user id 517 , belongs to group ram , having sh
shell ,home directory /root, account expires on 13/1/2007, and having name sapna.
[root@jmit ~]# adduser -u 517 -g ram -d /root -s /bin/sh -e 13/1/2007 sapna
[root@jmit ~]# passwd sapna
Changing password for user sapna.
New UNIX password:
Retype new UNIX password:
passwd: all authentication tokens updated successfully.
[root@jmit ~]# vi /etc/passwd
sapna:x:517:500::/root:/bin/sh
[root@jmit ~]# vi /etc/shadow
sapna:$1$rms3NFrh$L/ak5w8viFx3WeSh/DfGX.:13516:0:99999:7::13573:
In Fedora you might find this directory in /etc/rc.d/init.d. To control any of the scripts in
init.d manually you have to have root access.
Structure of command:
# /etc/init.d/command OPTION
Where command is the actual command to run and OPTION can be one of the following:
Option Description
start Start service.
stop Stop service.
restart If the service is running, stop it and then restart it. If it is not running, start
it.
reload Reload the configuration without stopping and restarting the service.
force-reload Reload the configuration if the service supports this. Otherwise, do the
same as if restart had been given.
status Show current status of service.
Most often you will use start, stop, or restart. So if you want to stop your network you
can issue the command:
/etc/init.d/samba stop
Or if you make a change to your network and need to restart it, you could do so with the
following command:
/etc/init.d/samba restart
Some of the more common init scripts in this directory are:
• networking
• samba
• ftpd
• sshd
• mysql
rc Files
Linux reads the rc (run command) files when the system boots. The init program initiates
the reading of these files, and they usually serve to start processes such as mail, printers,
cron, and so on. They are also used to initiate TCP/IP connections. Most Linux systems
have the rc command files in the directory /etc/rc.d.
/etc/rc.local
This option is the /etc/rc.local script. This file runs after all other init level scripts have
run, so it’s safe to put various commands that you want to have issued upon startup. This
is also a good place to place “troubleshooting” script in. Even after checking to make sure
the Samba daemon was setup to initialize at boot up. Simply placed the line:
# /etc/init.d/samba start in the /etc/rc.local script.
Network Configuration Files
1)/etc/host
The main purpose of this file is to resolve hostnames that cannot be resolved any other
way. It can also be used to resolve hostnames on small networks with no DNS server.
Regardless of the type of network the computer is on, this file should contain a line
specifying the IP address of the loopback device (127.0.0.1) as localhost.localdomain.
Aliases
The biggest benefit of using the /etc/hosts file is its ability to assign various aliases to an
IP address. An alias can be almost any alphanumeric combinationt, easy to remember,
and simple to type. For example, the any name is much easier to remember than
192.168.0.23.
Open /etc/hosts.
#vi /etc/hosts
You will see the following line
127.0.0.1 localhost.localdomain localhost
Normally, this line is the first entry in the hosts file, and it should remain so. There’s an
IP address (in this case, the loopback address), a hostname.domain name, and an alias.
The hostname is the name of the computer that you’re using, the domain is the domain of
your network, and the alias is a user-defined name for the computer. Let's enter a new
alias for the machine that you’re using. Let's say that the IP address of your machine is
192.168.0.23, the name of the machine is itdeptt, the domain is jmit, and the alias that
you’ve chosen is enggclg. This entry would appear like:
192.168.0.23 itdeptt.jmit enggclg
With this file in place, you can perform all of the networking functions by replacing
192.168.0.23 with enggclg.
2)/etc/resolv.conf
This file specifies the IP addresses of DNS servers and the search domain. The
resolv.conf file is used by the name resolver program. It gives the address of your name
server (if you have one) and your domain name (if you have one). You will have a
domain name if you are on the Internet.
A sample resolv.conf file for the system teji. jmit.com has an entry for the domain name,
which is jmit.com (teji is the name of an individual machine):
domain jmit.com
If a name server is used on your network, you should add a line that gives its IP address:
domain jmit.com
nameserver 192.168.0.1
If there are multiple name servers, which is not unusual on a larger network, each name
server should be specified on its own line.
3) /etc/sysconfig/network-scripts/ifcfg-<interface-name>
For each network interface, there is a corresponding interface configuration script. Each
of these files provide information specific to a particular network interface.
/etc/sysconfig/network
The /etc/sysconfig/network file is used to specify information about the desired
network configuration. By default, it contains the following options:
NETWORKING=boolean
A Boolean to enable (yes) or disable (no) the networking. For example:
NETWORKING=yes
HOSTNAME=value
The hostname of the machine. For example:
HOSTNAME=jmit.radaur.com
GATEWAY=value
The IP address of the network's gateway. For example:
GATEWAY=192.168.1.0
4) /etc/host.conf
The system uses the host.conf file to resolve hostnames. It usually contains two lines that
look like this:
order hosts, bind
multi on
These tell the system to first check the /etc/hosts file, then check the nameserver (if one
exists) when trying to resolve a name. The multi entry lets you have multiple IP addresses
for a machine in the /etc/hosts file (which happens with gateways and machines on more
than one network).
If your /etc/host.conf file looks like these two lines, you don't need to make any changes
at all.
5) /etc/networks
The /etc/networks file lists names and IP address of your own network and other
networks you connect to frequently. This file is used by the route command. One
advantage of this file is that it lets you call remote networks by name, so instead of typing
149.23.24, you can type jmit_net.
The /etc/networks file should have an entry for every network that will be used with the
route command if you plan on using the network name as an identifier. If there is no
entry, errors will be generated, and the network won't work properly. On the other hand,
if you don't need to use a network name instead of its IP address, then you can skip the
/etc/networks file.
#vi /etc/networks
loopback 127.0.0.0
localnet 147.13.2.0
jmit_net 197.32.1.0
it_net 12.0.0.0
At a minimum, you should have a loopback and localnet address in the file.
6) /etc/protocols
UNIX systems use the /etc/protocols file to identify all the transport protocols available
on the system and their respective protocol numbers.Usually, this file is not modified but
is maintained by the system and updated automatically as part of the installation
procedure when new software is added.
The /etc/protocols file contains the protocol name, its number, and any alias that may be
used for that protocol. A sample /etc/protocols file looks like this:
ip 0 IP
icmp 1 ICMP
tcp 6 TCP
udp 17 UDP
7) /etc/services
The /etc/services file identifies the existing network services. This file is maintained by
software as it is installed or configured.
This file consists of the service name, a port number, and the protocol type. The port
number and protocol type are separated by a slash, following the conventions mentioned
in previous chapters. Any optional service alias names follow. Here's a short extract from
a sample /etc/services file:
# network services
echo 7/tcp
echo 7/udp
ftp 21/tcp
telnet 23/tcp
smtp 25/tcp mail mailx
tftp 69/udp
You shouldn't change this file at all, but you do need to know what it is and why it is
there to help you understand TCP/IP a little better.
2) /etc/shadow
[root@jmit ~]# vi /etc/shadow
tajinder:$1$vQs3BuGW$NKFzioQnrNRsqiEsQeJyt.:13516:0:99999:7:7::
Here each field is also separated with colon. First field is login user's name, next field is
password denoted by encrypted form if no password is given than!! is displayed ,Next
fileld is day the password last changed (it counts days from 1/1/1970 to current date),
Next field is number of days a user can change password, Next field is maximum
password age, Next field is number of days before password expires when warning starts
appear to change password, Next field is number of days after password expires to wait
before disable account (often remain blank) and last field is expire date (Often blank)
2) /etc/gshadow
The /etc/gshadow file is readable only by the root user and contains an encrypted
password for each group, as well as group membership and administrator information.
Just as in the /etc/group file, each group's information is on a separate line. Each of these
lines is a colon delimited list including the following information:
• Group name — The name of the group. Used by various utility programs as a
human-readable identifier for the group.
• Encrypted password — The encrypted password for the group. If set, non-
members of the group can join the group by typing the password for that group
using the newgrp command. If the value of this field is !, then no user is allowed
to access the group using the newgrp command. A value of !! is treated the same
as a value of ! — however, it also indicates that a password has never been set
before. If the value is null, only group members can log into the group.
• Group administrators — Group members listed here (in a comma delimited list)
can add or remove group members using the gpasswd command.
• Group members — Group members listed here (in a comma delimited list) are
regular, non-administrative members of the group.
Here is an example line from /etc/gshadow:
general:!!:seema:teji,akshra
This line shows that the general group has no password and does not allow non-members
to join using the newgrp command. In addition, seema is a group administrator, and teji
and akshra are regular, non-administrative members.
Chapter 9
Compression, decompression, Backing up and restoring files in Linux
9.1 Compression and Decompression
Compression programs
Compression programs are sometimes used in conjunction with transport programs to
reduce the size of backups. This is not always a good idea. Adding compression to a
backup adds extra complexity to the backup and as such increases the chances of
something going wrong.
compress
compress is the standard UNIX compression program and is found on every UNIX
machine (well, I don't know of one that doesn't have it). The basic format of the compress
command is
[root@localhost]# compress filename
The file with the name filename will be replaced with a file with the same name but with
an extension of .Z added, and that is smaller than the original (it has been compressed).
A compressed file is uncompressed using the uncompress command or the -d switch of
compress.
[root@localhost]# uncompress filename or compress -d filename
Example:
[root@localhost]# ls -l ext349*
-rw-r----- 1 teji 17340 Jul 16 14:28 ext349
[root@localhost]# compress ext349
[root@localhost]# ls -l ext349*
-rw-r----- 1 teji 5572 Jul 16 14:28 ext349.Z
[root@localhost]# uncompress ext349.Z
[root@localhost]# ls -l ext349*
-rw-r----- 1 teji 17340 Jul 16 14:28 ext349
By convention, files compressed with gzip are given the extension .gz, files compressed
with bzip2 are given the extension .bz2, and files compressed with zip are given the
extension .zip.Files compressed with gzip are uncompressed with gunzip, files
compressed with bzip2 are uncompressed with bunzip2, and files compressed with zip
are uncompressed with unzip.
Media
Backups are usually made to tape based media. There are different types of tape. Tape
media can differ in
physical size and shape, and
amount of information that can be stored.
From 100Mb up to 8Gb.
Different types of media can also be more reliable and efficient. The most common type
of backup media used today are 4 millimeter DAT tapes.
dump on Linux
There is a version of dump for Linux. However, it may be possible that you do not have it
installed on your system. RedHat Linux does include an RPM package which contains
dump. If your system doesn't have dump and restore installed, you should install it now.
RedHat provides a couple of tools to install these packages: rpm and glint. glint is the
GUI tool for managing packages. Refer to the RedHat documentation for more details on
using these tools.
dump
The command line format for dump is
[root@localhost]# dump [ options [ arguments ] ] file system
[root@localhost]# dump [ options [ arguments ] ] filename
Arguments must appear after all options and must appear in a set order.
dump is generally used to backup an entire partition (file system). If given a list of
filenames, dump will backup the individual files.
dump works on the concept of levels (it uses 9 levels). A dump level of 0 means that all
files will be backed up. A dump level of 1...9 means that all files that have changed since
the last dump of a lower level will be backed up. Table shows the arguments for dump.
Options Purpose
Arguments Purpose
There are fields for each entry, each separated by a space or tab. First five fields we have to
specify when the command is to be run. Sixth field is the command itself. Issue following
command on terminal to see contents of crontab file.
[root@localhost]# vi /etc/crontab
01 * * * * root run-parts /etc/cron.hourly
Description of above entry
First is for minutes- 0-59
Second is for hour- 0-23
Third is for day- 0-31
Fourth is for month-1-12
Fifth is for weekday – 0-6 day of the week, o denotes the Sunday.
* represents the all .
By default cronjobs sends an mail to user account who runs the cronjobs. If we do not want
this we have to add following line at the end of the crontab file.
>/dev/null 2>&1
Example:
[root@localhost]# dd if=/dev/hda1 of=/dev/rmt4
With all the default settings copy the contents of hda1 (the first partition on the first disk)
to the tape drive for the system.
The mt command
The usual media used in backups is magnetic tape. Magnetic tape is a sequential media.
That means that to access a particular file you must pass over all the tape containing files
that come before the file you want. The mt command is used to send commands to a
magnetic tape drive that control the location of the read/write head of the drive.
[root@localhost]# mt [-f tapename] command [count]
Arguments Purpose
tapename raw device name of the tape device
command one of the commands specified in table
11.10. Not all commands are recognised
by all tape drives.
count number of times to carry out command
Parameters for the mt Command.
Commands Action
fsf move forward the number of files specified by
the count argument
asf move forward to file number count
rewind rewind the tape
retension wind the tape out to the end and then rewind
erase erase the entire tape
offline eject the tape
Commands Possible using the mt Command.
Example:
[root@localhost]# mt -f /dev/nrst0 asf 3
Moves to the third file on the tape
[root@localhost]# mt -f /dev/nrst0 rewind
[root@localhost]# mt -f /dev/nrst0 fsf 3
Same as the first command
The mt command can be used to put multiple dump/tar archive files onto the one tape.
Each time dump/tar is used, one file is written to the tape. The mt command can be used
to move the read/write head of the tape drive to the end of that file, at which time
dump/tar can be used to add another file.
Example:
[root@localhost]# mt -f /dev/rmt/4 rewind
Rewinds the tape drive to the start of the tape.
[root@localhost]# tar -cvf /dev/rmt/4 /home/jonesd
Backs up my home directory, after this command the tape will be automatically rewound.
[root@localhost]# mt -f /dev/rmt/4 asf 1
Moves the read/write head forward to the end of the first file.
[root@localhost]# tar -cvf /dev/rmt/4a /home/thorleym
Backup the home directory of thorleym onto the end of the tape drive.
There are now two tar files on the tape, the first containing all the files and directories
from the directory /home/jonesd and the second containing all the files and directories
from the directory /home/thorleym.