KEMBAR78
Unix Command | PDF | Computer File | Directory (Computing)
0% found this document useful (0 votes)
20 views75 pages

Unix Command

The document provides an overview of various Unix commands related to file system management, including commands for changing directories (cd), printing the current directory (pwd), creating directories (mkdir), removing directories (rmdir), and listing directory contents (ls). Each command is explained with syntax, examples, and options available for use. Additionally, it briefly mentions general-purpose utilities like cal and date for displaying calendars and current date/time.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views75 pages

Unix Command

The document provides an overview of various Unix commands related to file system management, including commands for changing directories (cd), printing the current directory (pwd), creating directories (mkdir), removing directories (rmdir), and listing directory contents (ls). Each command is explained with syntax, examples, and options available for use. Additionally, it briefly mentions general-purpose utilities like cal and date for displaying calendars and current date/time.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

Unix Commands

Unix Cmds
The file system cmds:--

-----------------------Genaral Structure Of Cmd:---------------------


$ cmd –[options][args]

List Of Cmds
1 ). CD (change directory):-
Suppose we have multiple dirs and we want to move from 1 to another then we can use cd cmd.
There are no options for the change dir cmd. The path name can be relative or absolute.
Generally it is relative.
 If there is no pathname arg the target is , the log-in (home dir).
 The log-in(home) dir can also be targetted by using the abbreviation(cd ~).
When cd cmd is used with specified arg it changes the current dir to the specified dir as arg..
Eg..

Cd <dir name>
 It will move to the specified dir.
cd /usr/spool/uucppublic
o/p-> You are now in the uucp spool directory.

 Cd .. && cd ~
 It will move to the parent dir from child dir.
 Cd /
 It jump to the root dir
 Cd
 It will move to the log-in dir

2 ).PWD (present /print working directory) :-


It is used for checking your current dir.
At a time one can located in only 1 dir. This dir is known as your current dir.
Eg.

1
Unix Commands
$ pwd
/home/john

3 ). Mkdir (make dir):-


Dirs are created with the mkdir cmd. The cmd is followed by names of dirs to be
created.
 It is external cmd.
 You can create a number of subdirectories with 1 mkdir cmd.
Syn:
Mkdir <dirname>
Or
Mkdir <dirname/sub dir name>>
Eg:
Mkdir fruits
Or
Mkdir fruits/apple/banana

You can also create multiple dirs at a time


Syn:
Mkdir <dir1> <dir2> <dir3>
Eg:
Mkdir grp1 grp2 grp3
These will create 3 subdirectories inside the current dir.
Sometimes creating dirs using mkdir may fail Due to the following reasons
1> The dir you want to create is already existing.
2> There may be an ordinary file by that name in the current dir.
3> The permission set for the current dir don’t permit the creation of files & dirs
by the user. You will most certainly get this msg if u try to create a dir in
/bin,/etc or any other dir that houses the Unix system’s file.
Some options of mkdir:-
 -m :
Suppose you want to have a dir which would have permission 754 irrespective
of the umask value u can use the cmd
Eg:-
Mkdir –m 754 newdir
The ls-l cmd is used to see permission i.e rwxr-xr--.
Mode to use for new directories. This allows you to specify what mode all of the new
directories will have when they are created. The default is 777 minus your umask
number or the system's default umask number.
 -p :

2
Unix Commands
You use the mkdir command to create new directories, thus building a hierarchy
of directories to maintain your files in an orderly fashion.

It may be useful for you to consider setting a standard naming convention or


structure for your directory hierarchy. Try to plan ahead when creating directories. The
most common mistake made by inexperienced UNIX users is the lack of subdirectories. It
is much easier to locate a file if you have your files categorized in subdirectories.

Eg:
Mkdir season/summer/mango
This cmd tells the unix sys to first create the season dir then inside it creates the
season dir and then inside it creates the mango dirs.

Parent directory creator. If you specify a pathname to create a new directory and
the parent directories do not exist, mkdir will create them as needed.
 The ls -l and ls -F command can be used to show if an entry in a directory is a
subdirectory.

4 ). Rmdir (remove dir):-

The external rmdir command removes a directory. The directory must be empty, if it is
not empty then unix will display an error msg. An empty directory only has two entries, the .
(dot) representing itself and the .. (dot dot) representing its parent directory.

The rmdir command is a safer way to perform directory removal than using the rm -r
command. It checks the directory for the existence of files and subdirectories. If any exist, rmdir
complains and exits without removing the directory.

You can’t remove a sub-dir unless you are in a dir which is the parent dir of the dir u want to
remove.

Generally a user is the owner of her home dir and she can create and remove sub-dir in this dir
created by her.

You can delete more than 1 dir at a time as shown below:

Syn:

rmdir directory_list
eg:
rmdir test test1

-p Removes empty directories specified in the directory path. If you specify a directory
by a pathname and its parent directories are empty, they also are removed. The name
of each directory is displayed on the standard output as it is removed. Directories that
are not removed are displayed on the standard error.

3
Unix Commands

Eg:
rmdir -p fruits/apple/banana

In the above ex we are in the parent dir of fruits. To apply this cmd with -p option
the dirs specified in the path as argument must be empty i.e it should contain only
that sub dir that is specified in the path not other than that, suppose if the fruits dir
contaoins some other file or dir and then if we apply this cmd then it will give an error
msg (dir is not empty).
-s Suppress any messages produced. Both standard error and standard output are
suppressed.

The rmdir command is useful for removing a directory. It is the restrictive or safe way
to remove a directory. It will complain if any files exist in the directory and fail. You
have to remove all files in the directory before rmdir will remove the directory. The
rm -r command is a much more powerful command, but with power comes the
hazards of carelessness. UNIX has no mercy when it comes to deleted files. Therefore,
be extremely careful if you venture to use the rm -r command.

5 ). Ls :-

The external ls command lists the contents of a directory. The ls command displays the
names of files and directories. Its options allow you to view additional information for each file
or directory. The following functions are provided:

* List filenames and directory names.


* Display the vital inode information about a file.
* Recursively list all subdirectories and their contents.
* Display nonvisual characters of filenames and directory names.
* Multiple formats provided for output.

If the name of the dir not provided it will display the content of the working dir..

Syn: ls [ -options] [ file_list ] [ directory_list ]

file_list :-One or more files ls will search for and attempt to display. Files beginning
with a period must be explicitly started with a period or the -a option must be used.

directory_list:- One or more directories ls will search for and attempt to display.
Directories may also begin with a period. If no arguments are given, ls displays all of the
filenames and directory names of the present working directory. The output is sorted
alphabetically.

4
Unix Commands
Eg.. ls –l fruits

Some options:-

-1 Display filenames and directories in single-column format.

$ ls -1

A1

A2

-F If the file is a directory, a slash (/) is placed after the name. If the file is marked as
executable, an asterisk (*) is placed after the name. If the file is a symbolic link, an at sign (@)
is placed after the name.

$ ls -F

a1 a2 a3 debo/

-R Recursively lists subdirectories. Each subdirectory that is encountered is listed in the


requested format. If you have four levels of subdirectories below your current directory,
ls will list all four levels.

Eg:- $ ls -R

a1 a2 a3 debo lsfile pooja

debo:

pooja:

fruits

pooja/fruits:

f1

-a List all entries including filenames beginning with a period (.). Without this option ls
does not list files starting with periods. If you use the -a option with the asterisk (*)
filename expansion character, the files beginning with a period will be displayed.
Without the -a option they would not be listed.

Eg: $ ls -a

. .sh_history a2 debo pooja

5
Unix Commands
.. a1 a3 lsfile

-c Sorts output based on the time of the last inode modification for each file. Mode change,
file created, link added, or time change cause inode changes. Changes how the -t and -l
options function. The inode is a header containing file information.

-d If the arguments are directories, list only their names. Suppresses the listing of a
directory's contents. Often used with the -l option to list the permissions of directories.

Eg : $ ls -ld

drwxr-xr-x 4 Hiren None 512 Sep 5 17:18 .

In the above eg we are at present in the hiren dir and the Hiren dir contains files
such as f1,f2 and dirs such as pooja, fruits, but by using this option it only displays the
present dir name , so it is often used with this –l option to list all the permissions.

-g Same as the -l option, except the owner field is not displayed (group only).

Eg:- $ ls -g

-rw-r--r-- 1 None 28 Sep 2 14:37 a3

drwxr-xr-x 2 None 512 Sep 5 17:18 debo

drwxr-xr-x 3 None 512 Sep 5 19:17 pooja

-i Precede each filename with its related inode number.

Eg: $ ls -i

2064622680 a1 1550512520 a3 1942844029 lsfile

101135124 a2 287726819 debo 1425752719 pooja

-l List contents of directory in long format. Displays the modes (see following section),
number of links, owner, group, number of bytes, time of last modification, and filename
for each entry. If the entry is a special file, then the major and minor numbers are
displayed in place of the byte count.

-n Same as the -l option, except the owner and group fields contain the actual user ID and
group ID.

-o Same as the -l option, except the group field is not displayed (owner only).

Eg :- $ ls -o

6
Unix Commands
-rw-r--r-- 1 Hiren 26 Jul 10 22:40 a1

drwxr-xr-x 2 Hiren 512 Sep 5 17:18 debo

-p If the file is a directory, a slash (/) is placed after its name.

Eg: - $ ls -p

a1 a2 a3 debo/ lsfile pooja/

-r Reverse the sorting order.

Eg:- $ ls -r

pooja lsfile debo a3 a2 a1

-s The file size is displayed for each entry. The size is in file system blocks. File system
blocks are usually 512, 1024, 2048, or 4096. Indirect blocks are included in this size.

Eg:- $ ls -s

total 8

2 p1 1 pooja 1 a3 1 a2

-t Sort entries by time stamp. The default is the last modification time.

Eg:- $ ls -t

p1 pooja debo a3 a2 lsfile a1

Here if we only apply the ls cmd then the o/p appears as follows.

$ ls

a1 a2 a3 debo lsfile p1 pooja

-u Sort entries by last access instead of last modification. Use with the -t and -l options.

-x List output in horizontally (across the screen) sorted columns. The number of columns
depends on the length of the longest filename and the screen width.

Eg: here if we apply only the ls command then the o/p appears follows:

$ ls

7
Unix Commands
a1 a3 f2 f4 lsfile pooja

a2 debo f3 f5 p1

But if we apply the ls –x then the output appears as follows

$ ls -x

a1 a2 a3 debo f2 f3 f4 f5

lsfile p1 pooja

If no options are given, each filename or directory name is listed on a separate line.

Long list using –l option shows the following information’s

 File Designation File Type

- Rehular File

d Directory

c Character Special

b Block special

l Symbolic Link

p FIFO

s Socket

-> Permissions

There are 3sets of permissions : owner, group, others. Each group has 3 possible
permissions: read (r), write (w) , execute (x) in that order. If a permission is granted , the
appropritate letter is shown. If it is not permitted , a dash is shown.

Links:

Links is a count of the number of the number of files that are linked to this directory or
file.

Owner:

8
Unix Commands
It is the user name for that account that owns the file. It is usually the same as log-in
name.

Group:

If the owner of the file is a member of a group then the group name is shown.

File size:

The file size in bytes.

last modifications:

the date and time of last modifications. If the file is more than a year old the time is
replaced by the year.

Filename: the name of the file . Normally , filename is just that, the name the owner used when
the file was created . Sometimes , however, you will see some additional characters in a
filename. Text editors often create a wrk file. When the editor is not terminated correctly,these
working versions can be left hanging around. Working files begin and/or end with a pound
sign(#) . hidden files are identified with a leading period. Occasionally you will see a system
file with a tidle (~) at the end of the name.

Genral purpose Utilities:--

1 ). Cal:-

The cal cmd is capable of diplay the whole Calendar of a particular year in the range of
1 to 9999. The o/p shows the current date as wel as the preceding and succeeding month.

Unix is not storing all the calendars in its memory but it is generating it by doing some
calculations when we invoke the cal cmd.

If you want to see only for a specific month then use it as follows:

$ cal 2 1997

In palce of 2 we can also use feb or just “f” but if we want January then we cannot use
only “j” bcoz “j” also stands for June, July, so if we become more specific and use “ja”
then it will work.

Following is the general format of the cal command.

cal [ [ month ] year ]

Arguments

9
Unix Commands
The following list describes the arguments that may be passed to the cal command.

Remember that a single argument will return the calendar for the given year. The year must be a
complete number, i.e., if you want to create the calendar for 1980, you must enter 1980. If you
just enter 80 the calendar for 80 A.D. is displayed.

The cal command is used to generate human readable calendars for everyday use. It is a useful
on-line utility that saves you from having to look up a day or date on a paper calendar.

2 ). Date:-

The date command displays the current date and time. The super-user (system
administrator) can use the date command to change the system's date and time. Any user can use
the date command to display the date and time in a standard default format or in a formatted
output.

Following is the general format of the date command.

date [ -u ] [ +format ]

eg:

$ date

Mon Sep 6 10:56:48 IST 2010

Or

$ date "+ today's date is :%D. The time is : %T"

today's date is :09/06/110. The time is : 10:57:44

For the date cmd , the format is +(plus) sign followed by text and a series of format codes
all enclosed in double quptes marks. Each code is preceded by a percentage (%) sign that
identifies it as a code.

The date cmd has only 1 user options and 1 argument. If no options is used the time is
local time. If a –u option is used , the time is GMT(Greenwich Mean Time).

Eg:

$ date –u

Mon Sep 6 05:32:11 GMT 2010

Format Descriptors

10
Unix Commands
The following is a list of format descriptors. Each descriptor must be preceded by a % character.
To display a % character enter %%.

Date format descriptors:

%A The full weekday (Sunday-Saturday)


%a The abbreviated weekday (Sun - Sat)
%B The full month name (January-December)
%b The same as %h
%c The country specific date and time format
%D The date (mm/dd/yy)
%d The day of the month (01 - 31)
%e The day of the month ( 1-31; single digits are preceded by blanks)
%h The abbreviated month (Jan - Dec)
%j The julian date, day of the year (001 to 365)
%m The month of the year (01 - 12)
%U The week number of year (00-53; Sunday is first day of week)
%W The week number of year (00-53; Monday is first day of week)
%w The day of the week (0=Sunday - 6=Saturday)
%X The country specific date format
%Y The year in century format(1990)
%y The current year (00 - 99)

Time format descriptors:

%H The hours (00 - 24)


%I The hours (00 - 12)
%M The minutes (00 - 59)
%p The string containing ante or post meridian indicator (defaults are AM or
PM)
%r The time (HH:MM:SS AM/PM)
%S The seconds (00 - 59)
%T The time (HH:MM:SS)
%x The country specific time format
%Z Timezone name

Output format characters:

%n Display a new-line
%t Display a tab

11
Unix Commands
%% Display a percent sign (%)

3 ). Echo:-

The internal echo command displays its arguments to your terminal. More precisely,
echo writes its arguments on the standard output. The arguments are strings separated by blanks
and terminated by a new-line. echo understands the more popular C-like escape character
sequences. Some of the features and uses of echo are:

* Display strings of text.


* Display variables.
* Display output with various formatting characters (SV only).
* Display ASCII characters based on octal escape sequences (SV only).
* Display menu screens for shell scripts.
* Display prompts for input to shell scripts.

COMMAND FORMAT

Following is the general format of the echo command.

echo [ -n ] [ arg ... ]

Options

The following list describes the options and their arguments that may be used to control how
echo functions.

-n Causes echo not to output a new-line character. Thus the text is displayed
and the cursor remains after the last displayed character. For example:
$echo -n "Enter choice: "
Enter choice: _

Basically you use the -n for shell script prompt lines.

The -n is also supported by the ksh print command. So if you have echo as an alias for print -
the -n option will work just like on BSD and csh echo.

Arguments

The arguments to echo are whatever text you wish to write to the standard output. If no
arguments are specified, then echo displays a blank line by writing a single new-line character.
You can use the following list of escape sequence characters to produce special output from
echo:

12
Unix Commands
CAUTION:
You must remember that the shell interprets the (backslash) as a special character.
Therefore, it is recommended that you place your echo arguments inside double quotes.

\a Bell

\b produces a backspace on the output.

\c writes the output, but does NOT terminate it with a new-line. Must be last.

\f produces a form feed.

\n produces a new-line.

\r produces a carriage return.

\t produces a tab.

\v produces a vertical tab.

\\ produces a backslash.

\0n produces the ASCII character with the octal code of n, where n is a 1-, 2-, or 3-digit octal
number representing the desired character.

The following examples show some of the useful aspects of this simple command.

Wildcards Matches Example Does’t match


* Every file
F* Every file whose name F2,f3 A1,af1
begin with f
*f Every file whose name Satf Stap,faF
end with f

*.* Every file whose name F2.dat bed


has a period

*.[ch] display all files ending P1.c, f1.h P1,f1


with a .c or .h

$TERM display the value of


the TERM variable

13
Unix Commands
4 ) printf :-

It is an alternative of echo cmd. The printf cmd is available on most modern unix
systems.

 It is an external cmd. only the bash shell has the printf built-in.
Eg..$ printf "pooja"
Pooja$_ // the prompt is located on the same line of output

Or
$ printf "pooja\n" //we have to explicitly write the \n for new line
Pooja
$_ // the prompt located at new line

Some Format strings for printf cmd:

%s - string

%30s - as above but printed in a space 30 char wide

%d -Decimal integer

%6d - as above but printed in a space 6 char wide

%o -Octal integer

%x -Hexadecimal integer

%f - floating point number

5 ).bc :-

Unix keeps a very useful feature handy. The calculator called be, possibly short for base
conversions, which is one of its functions, or the “ best calculator” .

 It is invoked by typing bc at the shell prompt. once you type bc at the prompt, you are
in the calculator mode, and the dolor prompt disappears
 Unix provides 2 types of calculator graphical object(xalc cmd) that looks like the one
and the text-base bc cmd.
 Bc belongs to family of cmds called filter that expect i/p from keyboard.
 The bc calculator can be used in decimal binary, octol, or hexa-decimal bases. The
base is specify by 1 of 2 expressions: i-base or o-base
 The i-base expr specifies that i/p will be in the specified base
 The o-base expr specifies the o/p base. If the i/p or o/p base is not define it is assume
to be decimal.

14
Unix Commands
 Scale is used to set the number of decimal places
 Ctrl+d is used to quit the calculator.

Eg..

$ bc

i/p- 12+8

o/p 20

scale=2

i/p- 19/3

o/p 6.33

ibase=2

i/p- 111

o/p 7

i/p- 111*111

o/p 49

obase=2

i/p- 5

o/p 101

i/p- 15/3

o/p 110

6).script:-

The external script command makes a copy (typescript) of a terminal session. When you
run script a new shell is forked. This new shell makes a complete copy of everything displayed
on your terminal. It reads standard input and output for your terminal tty and stores the data in a
file. The default filename is typescript.

To exit from a script session you simply press Ctrl-D or type exit.

15
Unix Commands
Following is the general format of the script command.

script [ -a ] [ file ]

The following option may be used to control how script functions.

-a Append the output of script to file. Normally script begins writing to a new file; if the
file exists it is overwritten unless you specify the -a option.

The following argument may be passed to the script command.

file The file script uses to save all data.


If no file is specified then the file named typescript is used.

The most common use of script is to make a copy of a terminal session. By starting script you
can save all the information, displayed on your terminal during a login session, to a file. You can
then print the file or view it with an editor.

Eg.

$ script f1 // start of scripting

$ pwd

/home/hello/sem5

$ // press ctrl+d for stop

Script done, output file is f1

$ cat f1 // viewing the script file f1

$ pwd

/home/hello/sem5

Script done on Mon Sep 06 20:23:01 2010

7 ).passwd:-

The external passwd command allows you to create or change the password
associated with your user name. The super-user (system administrator) can change any user's

16
Unix Commands
password and is not prompted for the old password. As a user you can only change your
password.

Following is the general format for the passwd command.

passwd [ user_name ]

passwd -s[ user_name ]

options:-

The following list describes the options used to control how passwd functions.

-d Deletes the password for user_name. The user_name will not be prompted
for a password.
-l Lock the password entry for user_name. No changes may be made.
-n min Set the minimum number of days between password changes.
-s Display (show) password attributes for user user_name. If no user_name is
specified, your login user_name is used. The format of the information is,
user-name status mm/dd/yy min max warn
or, if no password aging information is present
user-name status
Where
user_name The login ID of a user
status The password status
PS Passworded
LK Locked
NP No password
mm/dd/yy The date the password was last changed
min The minimum number of days between
password changes. The label MINWEEKS
specifies the default. It is located in the
/etc/default/passwd file and is set to NULL.
If min is greater than max, the user may not
change the password. Always use with the -
x option.
max The maximum number of days the password
is valid. The user is forced to change the
password every max days. The label
MAXWEEKS specifies the default. It is
located in the /etc/default/passwd file and is
set to NULL. If max is set to -1 then aging is

17
Unix Commands
turned off. If it is set to 0 then user_name is
forced to change the password at the next
login and aging is turned off.
warn The number of days before the password
expires, based on max, that the user_name
will be warned.
-a Display password attributes for all entries in the password file.

8 ).who:-

The external who command displays who is logged on the system. With no options, who
lists information about each user that is currently logged on to the system. The who command
reads the accounting file (/etc/utmp) and returns requested information. The default is the user
name, terminal line, and login time. The following table defines all information displayed based
on the header that who uses to describe each column of its output.

NAME The user name (LOGNAME).

STATE The write permission of the line (or hardware problem).

+ The line may be written to by other users.

- The line may only be written to by root.

? A problem has been detected with the line.

LINE The terminal tty name (ttyXX).

TIME The time you logged in to the system.

IDLE How long since you've typed something on your terminal. . It's been less than a
minute. HH:MM It's been HH hours and MM minutes. old It's been over 24 hours
or a boot occurred and no one has logged in on the line.

PID The process ID of your login process (login shell).

COMMENT Any comments related to your line's /etc/inittab entry. This information is placed
in the inittab by the system administrator. Common information is the location of
the terminal, the associated telephone number, type of terminal, or any other
pertinent information.

EXIT The system termination and the program exit values.

18
Unix Commands
Following is the general format of the who command.

who [-options][am i]

Options:

i) -H Causes columns headers to be printed. The possible headers are: NAME STATE
LINE TIME IDLE PID COMMENT EXIT

ii) -u Displays the IDLE field in addition to the default NAME, LINE, and TIME fields.
The IDLE field contains the time since any activity has occurred on a tty line.

am I Some systems display the hostname before your username.

Eg..

i) $ who

hello tty10 Sep 06 19:07

ii) $ who -Hu

USER LINE LOGIN-TIME IDLE FROM

hello tty10 Sep 06 19:07 .

iii) $who am i

hello tty10 Sep 06 19:07

The who am I cmd identifies the invoking user and lists the user name , terminal line, and the
date and time of log-in.

9) tty (Terminal Command):-

UNIX treats even terminals as files. The external tty command displays the name of your
terminal device path. Your terminal device path is used by UNIX to communicate with
your physical terminal. The tty command does not display your terminal type.

We can use tty even in an shell script to control the behavior of the script depending on
the terminal it is invoked from.

Syntax:-

Tty [–options][args]

19
Unix Commands
-s, --silent|quiet

Don't write anything, just return exit status. This option is obsolete.

EXIT STATUS

0 Standard input is a tty.


1 Standard input is not a tty.
2 An invalid option was given.

EG:- $ tty

o/p-> /dev/tty10

$ tty –s //it doesn’t display anything

$ echo $?

o/p-> 0 // The 0 (zero) reveals tty completed without errors.

10) sstty (Set terminal Command):-

The external stty command sets terminal I/O options for the standard input device. Your
standard input device is usually a /dev/ptyXX device driver. If you are on a network, it might be
a /dev/ttyXX device driver. Regardless of how you are connected to the UNIX operating system,
you have a terminal I/O device driver. The stty command can be used to set and reset how the
"tty" device driver functions.

Diiferent terminals have diff characteristics and your terminal may not behave in the way you
expct it to., for eg cmd interruption is not possible with[ctrl-d] on your sys. Sometimes you may
like to change the settings to match the ones used at your previous place of wrk. The sty cmd
helps straighten these things out, it both displays and changes settings.

Syntax:- stty [ -ag ] terminal-options

The following options may be used to control how stty functions.

-a Displays all terminal option settings.


-g Displays the current terminal option settings in a format you can use as
an argument to another stty command.

Eg:- $ stty

speed 19200 baud, 25 rows, 79 columns

kill = ^U;

20
Unix Commands
swtch = ^”; susp = ^Z;

-parenb

-parodd -cread -hupcl -cstopb -clocal

-ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr -iuclc -ixany -ixo

ff -imaxbel -iexten

-echonl -xcase -noflsh -tostop

-olcuc -onlret -ocrnl -onocr -ofill -ofdel

The keyboards take 2 forms

 Keyboard = value
 Keyboard or –keyboard. The –prefix applies that the option is turned off
For eg:- the setting intr=^c signifies that [ctrl-c] interrupts a prg.

Sty sane :- the sane arg sets the terminal configuration to a reasonable setting that can be
used with a majority of the terminals.

$ sty sane

The following table summarizes the common control key cmds.

Command Attributes(all I small letter) Default


Erase Text Erase ^h
End of the file Eof ^d
Kill command Kill ^u
Interrupt Command Intr ^c
Start Command Start ^q
Stop o/p ^d
Suspend command ^z

 Suppose you want to ENTER A PASSWORD THROUGH A SHELL SCRIPT (echo).


The echo setting has to be manipulated to let shell prgs accept a password – like string
that must be displayed on the screen. By deault, the option is turned on, but you can
turn it off in this way.

-keyword

Stty –echo

21
Unix Commands
11 ). Uname:-

The external uname command displays the name, node, version, release, and
hardware type of the current UNIX operating system. By default only the system's name is
displayed.

By default it displays the name of the Operating System.

Following is the general format of the uname command.

uname [ -option ]

The following list describes the options that may be used to control how uname functions.

-a Display all possible information. Invokes all other options except -S.
Eg.. uname -a
UWIN-NT local 2.00-5.1 2600 i686
-n Display the network nodename. The nodename is the name the system is
known by on a network.
Eg.. uname -n
local

Display the release number of the operating system.


-r Eg.. uname -r
2.00-5.1
-s Display the name of the UNIX system. This option is the default; if no
other options are listed, it is used.
Eg.. uname -s
UWIN-NT

Handling Ordinary Files

1 ) cat :-

The external cat command reads each file in the argument list and displays the data to the
standard output. It can read data from files or from the standard input. It only writes(>) to the
standard output. By using the shell redirection capabilities you can use cat to combine multiple
files into one large file, thus the name concatenate.

For such a simple command it is probably one of the most useful. Some of the uses of cat
include:

22
Unix Commands
* Display contents of ASCII files.
* Display control characters in a readable format.
* Make a copy of a file.
* Combine multiple files into one file.
* Copy input from your keyboard to a file.
* Send output to a pipe; useful for multiple file input.
* Combine input from your keyboard and a file into one output stream.

Following is the general format of the cat command.

cat [ - options ] [ file_list ]

The cat cmd is multi-purpose cmd:


i) To create a new file using (>) sign.
It is similar to copycon cmd of Dos.As we give i/p through keyboard we need
some way to store it.this is possible using this cmd.we need some way to tell unix
sys that we have inputted all the data and are at the end of the file by using ^+D.

Eg.. $ cat >f1


cat is external cmd
^+D
It creates the file f1.
ii) It is used to append text to file using (>>) sign
It is similar to edit cmd.
Eg..
$ cat >>f1
it is file handling cmd
^+D

$ cat f1
cat is external cmd
it is file handling cmd
iii) It is used to display the contents of the file
It is same as type cmd of dos.
Eg.
$ cat f1
cat is external cmd
it is file handling cmd
iv) It is used to concatenate 2 or more files at a time.
Eg..
$ cat f1 f2 >f3
$ cat f3 //Viewing the merged contents in the stored in the file f3
cat is external cmd
it is file handling cmd
fdg

23
Unix Commands
dfgdg

Some options of cat:


-s Error messages for nonexistent files are suppressed.
Eg.. $ cat f11
cat: f10: cannot open [No such file or directory]
$ cat -s f10
$_

-u Unbuffered raw output, the data is written to the standard output character-by- character.
Normally the output is buffered; written in blocks of characters.

-v Prints nonprinting characters in a visible form. Control characters are printed as ^X


(control-X). Non-ASCII characters (high bit set) are printed as M-x; x is the character
represented by the 7 low order bits.

-e Prints a $ (dollar sign) to represent the new-line character, i.e., the end of the line.
Eg.. cat -e n1
pooja yadav $
debo mitra$

-t Prints a ^I (Ctrl-I) in place of tabs.


Eg.. $cat -t n1
pooja yadav^I
debo ^Imitra

-n number lines

2) cp :-

The external cp command copies a file. It reads the contents of a file and creates a new
file or overwrites an existing file. There are two basic formats of the cp command that allow you
to:

* Copy one file to another


* Copy mutliple files to a directory
* Copy input from your keyboard to a file
* Copy a file to your terminal

Following is the general format of the cp command.

cp [ -option ] source_file destination_file


cp [ - option ] source_file_list destination_directory
cp -r [ - option] source_directory destination_directory

24
Unix Commands
The following list describes the options that may be used to control how cp functions.

-i Interactive confirmation is required. You are prompted if the copy will overwrite an
existing file. If your answer contains a y, the copy is performed. Otherwise, the copy
is not performed.
-p Preserve the characteristics of the source_file. Copy the contents, modification
times, and permission modes of the source_file to the destination files.
-r or -R Recursively copy any source directories. If a directory is given as the source file,
then all of its files and subdirectories are copied. The destination must be a
directory.

The first format copies one ordinary file to a new file. The source_file is the pathname of the file
being copied. The destination_file is the pathname of the file being copied to by cp.

The second format will copy one or more files to a specific directory. The source_file_list is a
list of pathnames of the files being copied. If you specify a directory with the -r option, the entire
directory tree is copied to the destination directory.

The third format allows you to copy an entire directory structure to a new directory.

If the destination_file exists and you have write permissions, cp will overwrite the contents of
the file. The access permissions and ownership of the overwritten file will be used for the new
destination_file.

If the destination_file does not exist, the access permissions of the source_file are used. Your
ownership and group IDs are used for the new file if you are the user performing the cp
command.

Cp is often used with short hand notation, .(dot), to signify the current dir as the destination for
instance to copy a file . profile from /home/Sharma to your current dir you can use either of the
2 cmds:

Cp / home / Sharma /.profile .profile //destination is the file

Cp / home / Sharma /.profile . //destination is the current dir

Unix sys uses the * to frame a pattern foe matching more than 1 file,if there were
only 3 file names in the curr dir having the common strings chap,you can compress the above
sequence using the * as a suffix to chap

Cp chap* progs //copies all the files beginning with chap

Wildcard copies :-

Wildcards can be used to copy files as long as the destination is anoyher dir. You can not
use wildcards if you are coping to and from the same dir.
25
Unix Commands
Eg..

$ cp dirA/f* dirB // this is possible

$ cp dirA/f* dirA // this is not possible

3) rm

The external rm command removes (deletes) files or directories. The remove command
actually removes the specified links to a file. Since a file can have more than one link,
performing a remove may not delete the contents of the file. Instead only the reference to the file
is lost. Another reference may still exist. If all links (filenames) to the file are removed, the file is
deleted and the contents are lost. You cannot undelete a file on a UNIX System.

The rm command removes the entries for one or more files from a directory, thus
removing a link to the inode. If the last link pointing to the inode is removed, then the contents of
the file can no longer be referenced. The inode and contents are still on the disk but you have no
way to access them.

You do not have to have read or write permissions on a file to remove it. Although you
do have to have write permission for the directory to remove a file from the directory. If you do
not have write permissions for the file and you are using rm from your terminal, rm prompts
with the file's permissions and waits for a confirmation. To perform the removal, type any string
beginning with a "y."

Syntax : rm [-options] [file name ] [directory name]

rm [ -fi ] file_list
rm [ -fir ] directory_list [ file_list ]

Options

The following list describes the options used to control how rm functions.

-f Forces the removal of all files listed. Does not check to see if the file is
writeprotected or not. Does not prompt for confirmation. If the directory is
writeprotected the files are NEVER removed.
-i Interactive file removal. Before each file is removed you are requested to
respond with a confirmation. Any string beginning with a "y" removes the
file. If used with the -r option, confirmation is asked for each directory. The
-i option overrides the -f option and is effective even if the standard input is
not your terminal keyboard.
-r Recursively removes files and directories. All files are removed from each
directory. Each directory is then removed. If a file is writeprotected (you do

26
Unix Commands
not have write permission) then rm prompts you for confirmation to remove
the file.

Wildcard remove

Remove can be used with wildcards.This option is highly dangerous and


should be used with caution. It is generally considered a good idea to use the echo cmd to test the
effect before actually executing a remove.

Eg..

$ echo rm –r f* //it wil display the list of files that will be removed by that cmd..

o/p rm –r file1 flie2 f3.bak

$ rm -r f3.bak //it will remove the file f3.bak

Make sure you are doing right thing before you use ” rm *” . be doubly sure
before you use rm -r f*. The first cmd removes only ordinary files in the current dir .the 2nd one
removes everything files and dirs . if the root user invokes rm – r f* in the root dir the entire
Unix sys will be wiped out from the Unix sys.

4) mv :-

The external mv command moves a file from an existing location to a new location. It is also
used as the rename command to change the name of a file. It has three formats allowing you to:

* Rename a file with a new filename.


* Move one or more files to reside under a different directory.
* Rename a directory with a new directory name.

The general formats of the mv command follow.

mv [ - options] filename new_filename


mv [ - options] filename directory
mv [ - options] old_directory new_directory

Only one option may be used to control how mv functions.

-f Force the move to occur. The response of "yes" is assumed and the move is
performed. No interactive response is requested.
If the standard input is not the terminal keyboard, then the -f option is
assumed.

27
Unix Commands
-i The command runs in interactive mode. If the destination file being moved
to already exists, mv prompts you with the filename being moved followed
by a question mark. If you respond with any string beginning with a y, the
move is performed. Any other response causes mv to skip to the next move.
- Interpret all arguments that follow as filenames. This allows you to specify
filenames and directories that begin with a hyphen (-). This can become
helpful if a filename is created that begins with a hyphen.

Arguments

following list describes the arguments that may be passed to the mv command.

filename The existing file being moved or renamed.


filename_list The names of files to be moved to a new destination. The destination must
be a directory.
new_filename The new filename the existing file will be given.
directory The name of the directory the files will reside in after the mv is performed.
old_directory The existing directory being renamed.
new_directory The name of a newly created directory. The destination directory.

The first format renames a file. The name of the existing file is changed to the name of
new_filename. The new_filename and the existing filename cannot be the same full pathname.
They may have the same filename, providing they reside in different directories. If the new
filename is an existing file and you have write permissions, its contents are lost. If the destination
is a link to another file, the link is lost and the destination filename points to the new file.

The second format moves one or more files to a different directory. The filename_list is a list of
pathnames being moved. The basename of each pathname is used for the destination filename in
the specified directory. For example, if you wanted to move all files beginning with memo to the
memodir directory, you would type mv memo* memodir.

The third format renames a directory. The name of the directory is changed to the new directory
name you specify. The same restrictions apply to directory renaming as file renaming. If you are
renaming directories, the two directory names reside in the same file system.

The mv cmd serves 2 essential purpose. The 1st purpose is to physically remove the file from its
current location and copy it at its destination. The next goal is to rename files and directories that
are specified.

Before mv performs these steps it checks the destination file for write permissions. If you do not
have write permissions on the destination file or directory, mv will display the mode (chmod;

28
Unix Commands
Module 17) and request a response from standard input. If the input line you type starts with a
"y," mv attempts to move the file to the target. If the ownership permissions allow you to write
to the target, the move will occur. If you do not have permission to write to the destination, the
mv will fail.

If you are moving files across file systems, the mv command performs a cp and then an rm
command. The file is copied to its destination and then the existing file is removed. The new file
is owned by you if you moved it.

Cp ,mv and rm work by modifying the dir entries of the files they access. Cp adds as an entry to
the dir with the name of the destination file and inode number that is allotted by the kernel . mv
replaces the name of an existing dir entry without disturbing its inode number. Rm removes from
an entry from the dir.

5) More:-

The external more command allows you to peruse a file on your terminal. It is a filter that reads
the standard input or files. It lets you view one screen of text at a time.

The page command performs the same function as more with a different screen control. The
screen is cleared before each full screen of text is displayed. It also displays ROWS - 1 rather
than ROWS - 2 rows of text, where ROWS is the number of lines on your terminal screen

The most common use of more is to display large files or output from a pipe to your screen one
screen at a time. It is also useful for help screens in shell applications. You can create a help file
exactly a multiple of 22 lines and have more display it within your shell script. This provides
you with a professional and consistent interface for your users.

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

Syntax: more [-options] [file-list]

The following list describes the options and their arguments that may be used to control how
more functions.

-c Draw each screen of text line-by-line. Each line is erased just before the
new text is written to the line. This provides a more controlled screen,
allowing for easier reading of existing text while new text is being
displayed. If the terminal cannot perform a clear-to-end-of-line function, the
option is ignored.

29
Unix Commands
-d Changes the prompt to be "Press space to continue, 'q' to quit." from "--
More--(9%)." If an incorrect response is entered, then the message "Press 'h'
for instructions." is displayed instead of sounding the terminal bell. This is
useful for application shell programming where more is used as an interface
to unsophisticated users.
-f Do not fold long lines. Count logical lines instead of screen lines. Normally
more truncates lines longer than the width of the screen (environment
variable COLUMNS). This option allows you to pipe nroff output to ul
then into more without having lines folded (truncated) because of
embedded escape sequences.
-l Do not process form feeds as special characters. Normally more pauses
before each form feed, assuming the end of a page of text has been reached.
A form feed at the beginning of a file normally causes more to clear the
screen before displaying text from the file.
-s Squeeze out adjacent blank lines. Two or more blank lines grouped together
are reduced to one blank line. This increases the amount of text displayed
on the screen. It is very useful when viewing nroff output.
-u Suppress underlining and standout (bold) mode. The normal sequences for
underlining and standout mode are stripped from the output.
-w Prompts and waits for any key to be pressed before exiting. By default
more/page will exit without waiting upon reaching the end-of-file.
-lines Specifies the number of rows (lines) to display on your terminal screen.
Resets the size, in lines, of your window to rows
+nmbr Begin displaying text at line number linenum of the input.
+/ptrn Begin displaying text two lines before the line containing the regular
expression pattern.

More has many internal cmds:

q – to exit from more

f- to scroll forword one screen(or spacebar)

b- to scroll back one screen.

j- to move 1 line forward at a time

k- to move 1 line at a time.

v- to invoke vi editor.

Exit from vi editor returns you to move once again.(:q!)

30
Unix Commands
This internal cmds are not displayed on the screen.

The more cmd displays a ---More--- prompt at the end of each page of the file that is being
displayed. To continue scrolling with the more cmd, the user has to press the “Spacebar” instead
of the “Enter Key” here, he can scroll one line of the o/p at a time.

Additionally the more cmd displays the percentage of the contents of the file that you have
viewed.

The more cmd also offers a help screen when you press” h “ key.

More also works with multiple files. It sequentially displays all the files pausing additionally
whenever a change of file occurs.

: n – to switch to the next line.

: p – to switch to the previous line.

6) file :-

The file command determines what type of data a file contains. It returns a brief
explanation of what type of data it believes is in each file.

Even though we know that files are of 3 types, you may often need to know more about these
files. For instance, a regular file may contain plain text, a C prg or executable code. UNIX
provides the file cmd to determine the type of file, especially of an ordinary file. You can use it
with one or more filenames as args.

Eg $file archive.zip

Archive.zip: ZIP archive

File correctly identifies the basic file types (regular, directory or device.) for a regular file it
attempts to classify it further. Using the * to signify all files, this way file behaves on this
system having regular files of varying types:

Eg: $file *

a1: short text

a2: short text

a3: short english text

copy: directory, searchable

31
Unix Commands
copy1: directory, searchable

dp: directory, searchable

f1: short english text

This cmd identifies the file type by examining the magic number that is embedded in the
first few bytes of the file. Every file type has a unique magic number.file recognizes text
files,and can distinguish between shell prgs, c source and obj code. It also identifies DOS
executables , compressed files, PDF documents and even empty files. While this method of
identifying files is not wholly accurate,it’s a reliable indicators..

7 ) wc : -

The external wc command counts the characters, words, and lines in a file and displays the
output on your screen. The word delimeters for wc are space, tab, and new-line. The delimeter
for a line is new-line. The input may be the standard input, therefore wc is a filter.

The features of wc are:

* Counts the number of characters in a file.


* Counts the number of words in a file.
* Counts the number of lines in a file.
* Reads from a file.
* Reads from the standard input.
* Writes to standard output.
* Handles multiple files, provides counts for each file read.

Following is the general format of the wc command.

wc [ - option ] [ file_list ]

The following options may be used to control how wc functions.

-c Count and display only the number of characters contained in the given files.
-l Count and display only the number of lines contained in the given files.
Lines are defined as ending with new-lines.
-w Count and display only the number of words contained in the given files.
Words are defined as ending with spaces, tabs, or new-lines.

If no options are specified, wc returns the count for lines, words, and characters (the default is all
3 options). Thus wc assumes the -lwc options. The counts are displayed in the order the options
are given. For instance, if you specify -cwl, wc displays characters, words, and lines followed by
the filename.

32
Unix Commands
The following argument may be passed to the wc command.

file_list One or more files to be counted. The requested counts will be displayed.
Each filename will be displayed on a line by itself, preceded by the
appropriate counts.
If no files are given, then wc reads from the standard input, which may be a
pipe, indirection, or your keyboard.

Eg..

$ wc a1

o/p 4 4 26 a1

The o/p can be interpreted as follows :

The file a1 contains 4 line , 4 word and 25 characters. The spaces between each word and
the newline character after each line are also included in the character count.

We can use multiple file with wc cmd at a time

i) Eg ..

$ Wc a1 a2 a3

o/p 4 4 26 a1

4 4 23 a2

4 4 28 a3

12 12 77 total

ii) Eg..

$ wc -l a1

4 a1 // Number of lines

$ wc -c a1

26 a1 // Number of characters

$ wc -w a1

4 a1 // Number of word

33
Unix Commands
8 ) od (Displaying file in non- ASCII format) :-

The external od command provides a way to view the contents of a file byte-by-byte or word-by-
word. A byte is eight bits and a word is two bytes (16 bits). The format of each byte or word can
be octal, decimal, hexadecimal, or ASCII. You can use od to display a file that has special
character sequences, such as control characters or extended ASCII characters.

The od command displays bytes and words of information. These display formats are not
dependent upon the computer hardware.

Following is the general format of the od command.

od [ -options ] [ file ]

The following list describes the options and their arguments that may be used to control
how od functions.

-b Displays each byte in octal format. For example, a file (pups) containing the
word PUPPIES is displayed as
od -b pups
000000 120 125 120 120 111 105 123 012
The first set of zeros is the address of the first byte displayed on the current
line. The 120 is the octal representation for P.
-c Displays each byte in its ASCII character format. Nonprinting characters
have the following special representations.
Notation Meaning ASCII Label
\0 Null NUL
\b Backspace BS
\f Form feed FF
\n New-line NL
\r Carriage Return CR
\t Tab HT
\ooo Octal Representation of
character
All nonprintable characters that do not have a special symbol are
represented using their octal representation.

The od command can be used to view the contents of a file containing special nonprinting
characters. You may find it useful to look at binary files such as compiled C programs containing
machine code or data files containing data in binary format. Typically, it is used more by
programmers than general users but it is one of those commands worth knowing about when you
need it.

34
Unix Commands
The following describes the argument that may be passed to the od command.

file The name of the input file to be displayed in od


format.

If no file is specified od reads from the standard input. Thus you can use od to read input from a
pipe or straight off your keyboard. If you use it from your keyboard, no output is displayed until
you press Return or Ctrl-D.

Eg.. $ cat >k1

i m ^g

$ od -b k1

0000000 151 040 155 040 136 147 012

0000007

$ od -c k1

0000000 i m ^ g \n

0000007

$ od -bc k1

0000000 151 040 155 040 136 147 012

i m ^ g \n

0000007

 The tab char [ctrl+i],is shown as \t and the octol value 011.
 The bell char [ctrl+g],is shown as 007. Some sys show it as \a.
 The formfeed char [ctrl+L],is shown as \f and the octol value 014.
 The LF (linefeed or new line) char, [ctrl+j],is shown as \n and the octol value 012.

Note that od makes the new line char visible too.

9 ) cmp (comparing 2 files):-

The external cmp command compares two files. If the files are the same, cmp returns
with no output. If the files are different, cmp returns the line number and byte position of the

35
Unix Commands
first difference. Only two files may be compared at one time. The unique features of cmp over
other file comparison tools are:

* Data can be of any type; does not have to be ASCII characters.


* Data does not have to be sorted.
* Execution is faster than most other compare programs.

Following is the general format of the cmp command.

cmp [ -option ] - file2


cmp [ -option] file1 file2

The first format is used to compare the standard input to a file (file2). The second compares two
existing files. You may find it helpful to use the first format in a pipe. The cmp file1 - format is
not valid.

The cmp command is used to compare files for possible differences. You may want to think of it
as the file comparison utility that can compare two files of any type for a difference of equality.
It performs faster than the other file compare utilities. This is because it is a simple program
comparing byte by byte. It can be thought of as a binary yes or no type file comparison program.
Yes, the files are the same or no, the files are different. Thus it lends itself to shell scripts that
need to check for files that match exactly, but they don't care what is wrong.

One example is the removal of like files. You can use the cmp command to compare files. If no
output is returned (the return code is 0), you know the files are identical and thus can proceed to
remove one of the files. On the other hand, if you want to make a backup copy of a file, you may
want to use cmp to ensure the new copy is identical to the original.

The return codes of cmp may be used to control conditional statements within shell scripts. The
following list describes the meaning of each code.

0 The files are identical.


1 The files are NOT identical.
2 There is a problem reading a file or with an option you provided.

The following list describes the options that may be used to control how cmp functions.

-l Display the byte position in decimal and the bytes that differ in octal for each
occurrence of a difference.
-s Do not display information for differing files. Only set the return code to 1.

The following arguments may be passed to cmp.

- Read from the standard input for the first input files.

36
Unix Commands
file1 The first of two files to compare. This may be a text or binary type file.
file2 The second of two files to compare. This file may also be text or binary.

Eg.. If the files are diff

$ cat log

name line

user1 ttyla

user2 tty2c

accell tty2d

$ cat log-user

name line

user1 ttyla

user2 tty2c

infress tty2d

$ cmp log log-user

log log-user differ: char 35, line 4

If 2 files are identical, cmp displays no message but simply returns the prompt.

Eg..

$ cp log log1

$ cmp log log1 // no message will display

10 ). Comm. (common):-

The external comm command compares two lists of sorted ASCII data (files).

The default output is three columns; lines only in file1, lines only in file2, and lines in both files.
Lines common to both lists or lines only in one of the two lists may be displayed. The two lists
may be stored in files or one may be the standard input. The possible output displays can consist
of:

37
Unix Commands
* Lines only existing in the first file
* Lines only existing in the second file
* Lines existing in both files
* Any combination of the above

Following is the general format of the comm command.

comm [ -123 ] - file2


comm [ -123 ] file1 file2

The first format is used to compare the standard input to a file (file2). The second compares two
existing files. You may find it helpful to use the first format in a pipe.

The following list describes the options that may be used to control how comm functions.

-1 Suppress the displaying of column 1. Lines existing only in file1 are not
displayed.
-2 Suppress the displaying of column 2. Lines existing only in file2 are not
displayed.
-3 Suppress the displaying of column 3. Lines existing in both files are not
displayed.

The following list describes the arguments that may be passed to the comm command.

- Read from the standard input. The input is read from your keyboard or a pipe
instead of a file.
file1 The first file to read input from and compare against file2.
file2 The second file to read input from and compare against file1.

The return codes of comm may be used to control conditional statements within shell scripts.
The following list describes the meaning of each return code.

0 The files are identical.


1 The files were NOT identical.
There was a problem reading a file or with an option you
2
provided.

You can use the comm command to compare two lists of data. The two lists must reside in
different files. You can compare for common items existing in both sets of data or for data that
exists in one file and not the other.

Since it can only function on ASCII files, it is limited to text type files.

Eg..

38
Unix Commands
$ cat >user

barbara

george

scott

$ cat >mgnt

barbara

kathy

scott

$ comm user mgnt

barbara

george

Kathy

Scott

12 ) diff :-

The external diff command compares two text files for differences. It determines which
lines must be changed to make the two files identical. The diff command scans the two files and
indicates editing changes that must be made to the first file to make it identical to the second file.

Following is the general format of the diff command.

diff [ -options] file1 file2

diff [ -options] file1 dir

diff [ -options] dir file2

diff [ -options] dir1 dir2

The following list describes the arguments that may be passed to the diff command.

39
Unix Commands
file1 The first input file used in the comparison. If file1 is a directory name, the
file2 file in directory file1 is used for comparison. For example, if you
specify,
diff adir afile
diff uses adir/afile afile for the two files.
file2 The second input file used in the comparison. If file2 is a directory, the
second file is set to file2/file1.
dir1 The first directory containing files used for comparison.
dir2 The second directory containing files used for comparison.

The basic use of diff is to find text differences between two files

The following list describes the options and their arguments that may be used to control how diff
functions.

Comparison control options:

-b Causes blanks (spaces and tabs) to compare equally even if an unequal


number of blanks exist. All trailing blanks are ignored. For example, if the
first line was in file1 and the second line was in file2, they would compare
as equals.
file1: A sample line of text here
file2: A sample line of text here
-i Causes the case of letters to be ignored. For example,
THE BIG dog ran fast.
and
The big dog ran fast.
match as equal lines.
-w Causes all white spaces (blanks and tabs) to be ignored. For example,
if ( x == y )
and
if(x==y)
compare as equals.

The output of diff varies depending on the options you specify. The n represents line numbers
and line represents the text on a line. The greater than and less than symbols are used to
distinguish which lines belong in which file. For example,

< Always a line from file1.


--
> Always a line from file2.

shows that the first line resides in file1, the -- separates the two files' output, and the third line
resides in file2.

40
Unix Commands
Appending

The append string informs you which strings exist in file2 but not in file1. Therefore, the lines in
file2 must be appended after the displayed line in file1.

n1an2,n3 <line n2
...
<line n3

The first line informs you to append lines n2 through n3 from file2 after line n1 in file1. The lines
of text following the < are to be copied from file2 and placed in file1 after line n1.

Changing

The change string informs you which strings in file1 must be changed to make the two files
agree. The change is basically a delete and append command. It replaces entire lines in file1 with
entire lines from file2.

n1,n2cn3,n4 Informs you to replace lines n1 through n2 in file1 with


<line n1 lines n3 through n4 from file2.
...
<line n2
--
>line n3
...
>line n4

Deleting

The delete string informs you which strings do not exist in file2 but do exist in file1. The lines in
file1 must be deleted to make the files conform.

n1,n2dn3 Informs you to delete lines n1 through n2 in file1. File1


<line n1 is identical to file2 up to line n3 in file2.
...
<line n2

$ diff user mgnt

0a1 // Append after line 0 of first file(user).

> Andrew // this line

41
Unix Commands
2,4c3 // change line 2 to 4 from file1

< david

< george

< jill

---

> Kathy // with this line.

6d4 // delete line 6 from user file. B’coz it diifers from mgnt by 4 characters (i.e. tina)

< tina

** Compressing and archiving a file :-

To conserve disk space you’ll need to compress large and infrequently used files.
Moreover , before sending a large file as an e-mail attachment, it’s good manner to compress the
file first. Every unix sys comes with some or all of the following compression and
decompression utilities .

Gzip and gunzip (.gz)

Bzip2 and bunzip2(.bz2)

Zip and unzip(.zip)

You ‘ll all of this prgs on Solaris & Linux. The extension acquired by the compressed filename is
shown in parenthesis. The degree of compression that can be achieved depends on the type of
file, it’s size and the compression prg used. Large text files compressed more but gif and jpeg
img files compress very little b’coz they hold data in compressed in form.

Apart from compressing you will also need to group a set of files into a single file, called an
archive. The tar and zip cmds can pack an entire directory structure into an archive. You can
send this archive as a single file, either using ftp or as an email attachment, to be used on a
remote machine. An additional layer of compression helps bring down the file size, the reason
why tar is often used with gzipand bzip2 for creating a compressed archive.zip handles both
function itself.

1) Gzip AND gunzip: Compressing and decompressing Files

42
Unix Commands
We’ll monitor that the size of one HTML and one postscript as they go through a number of
compression and archival agents. Lets start with gzip, it works with one or more filenames.

It provides the extension .gz to the compressed filename and removes the original file.

Syntax : gzip [-options] filename

Eg : $ wc -c d2

253 d2

$ gzip d2

$ wc -c d2.gz // after applying the original file is removed and a new file with the
same name but with extension .gz is placed in its position.

185 d2.gz

Uncompressing the compressing file

Uncompressing a gzipped file (-d) To restore the original and uncompressed file, you
have 2 options:

A) Use gzip -d
B) Use gunzip

With one or more filenames as args; the .gz extension is optional again:

Syntax :

Gzip –d <filename>

Gunzip <filename>

Eg 1): $ gzip -d d2

$ wc -c d2

253 d2

Eg 2): $ gunzip d2

$ wc -c d2

253 d2

43
Unix Commands
2) Tar : (Tape archive) The archival program

The external tar command is a tape archive program. It is used to archive files
from disk to tape. The media does not have to be tape. You can create a tar file on disk,
diskette, cartridge tape, or 9-track tape. You also use tar to retrieve archived files from a
tar file.

The most common use of tar is to create archive tapes and extract files when
needed. The tar command is more sophisticated than the cpio program. It can update the
existing archive file without having to rewrite the file from the beginning. It can also be
used to copy directory structures from one directory to a new directory.

Following is the general format of the tar command.

tar [-options] block device filelist


tar [-options] block device [ filelist ]
tar [-options] device
tar [-options] block device [ filelist ]
tar [-options] device [ filelist ]

These options specify what function tar is to perform.

-c Creates a new archive file. The writing starts at the beginning of the archive. The
-r option is automatically assumed.
-r Replaces the named files. The files are written on the end of the tar file.
-t Displays a table of contents of all files contained in the tar file.
-u Updates the archive file. Adds the files to the tar file if they are not already
archived and if they have been modified since the last archive was written.
-x Extracts files from the tar file. If no files are listed, all files are extracted from the
tar file. If multiple versions of a file exist in the tar file, only the last (latest)
version is extracted. If the named file is a directory, then the entire directory tree
is extracted. If a file no longer exists on disk, the file is created with the modes
from the archived version of the file. The set-UID and set-GID bits are not set on
extracted files unless you are super-user.
-f arch Specify the archive arch
-v Diplays the progress while tar works. All the msga about the
action of the tar cmd are displayed for the user’s reference

The following list describes the arguments that may be passed to the tar command.

block Specifies the blocking factor for raw devices. The default is set to 1. The possible
block sizes range from 1 to 64.
device The name of the device to be used for the archive. Each system usually has
multiple device drivers for each physical media device.

44
Unix Commands
The tar cmd saves and restores files to and from an archive medium which is typically a storage
device, such as a tape or a floppy disk. This cmd is very useful in taking backups of files but
offers some a multitude of options to make difficult for the user. Note that all the users can use
the tar cmd; it is not restricted only to the super user. However a normal user will not be allowed
to take backups of system files.

The actions of the tar cmd are controlled by the key arg. The key is a string of a char containing,
at most, one function letter and possibly, one or more function modifiers.

The function letters decide precisely what function the tar cmd must perform (backup or restore)
and function modifiers control the manner in which the function must be executed. There is great
emphasis on order. The function letters must always precede the function modifiers.

Creating the Archive (-c)

To create an archive, we need to specify the name of the archive (with –f) , the copy or
write operation (-c) and the filename as args. Additionally, we will use the –v (verbose) option to
display the progress while tar works. This is how we create a file archive, archive.tar, from the
two uncompressed files used previously:

$ tar –cvf archive.tar libc.html User_guide.ps

a libc.html 3785K // -v (verbose) displays list

a User_Guide.ps 364K // a indicates append

By convention, we use the .tar extension, so you’ll remember to use the same tar command
for extraction. We created an archive two or ordinary files, but tar also behaves recursively to
back up one or more dirs. In the foll ex, tar fills the archive progs.tar with 3 dir structure:

Tar –cvf progs.tar c_progs java_progs shell_scripts

The same tar cmd is used to extract files from archive.

Using zip with tar If the created archive is very big, we can compress it with gzip:

gzip archive.tar

This creates a tar-gzipped file, archive.tar.gz. this file can now be sent out by ftp or as a
email attachment to someone.

Extracting files from Archive (-x)

Tar uses the –x option to extract files from an archive. You can use it right away on a .tar
file, the one we just used to archive 3 dirs.

45
Unix Commands
Tar -xvf progs.tar //extracts 3dirs

But to extract files from a .tar.gz file (like archive.tar.gz), you must firat use gunzip to
decompress the and archive and then run tar:

$gunzip archive.tar.gz // retrives archive.tar

$ Tar -xvf archive.tar //extract files

X libc.html, 3875302 bytes, 7569 tape blocks //x indicates extract

X user_guide.ps, 372267 bytes, 728 tape blocks

You’ll now find the 2files in the current dir. Selective extractions is also possible. Just
follow the above cmd line with one or more filenames that have to be extracted:

Tar -xvf archive.tar user_guide.os //extracts only user_guide.os

Viewing the archive (-t)

To view the content of the archive, use the –t options. It doesn’t extract
files but simply shows their attributes in a form :

Eg: $ tar -tv d2

/dev/rmt8 volume 1 in tar format

-rw-r--r-- 1 Hiren None 253 Sep 10 18:43 d2

1 file, 4 blocks

3) Zip and unzip (compressing and archiving together)

.zip doesn’t compress as much as bzip2 but it combines the compressing dir structure,
you can use only one ----zip. All the letters of the alphabet are available as its options bur
we will consider only few of them.

Zip requires the 1st argument to be the compressed filename; the renaming args are
interpreted as files and dirs to be compressed. The compression in the previous example
could have been archived with sip in the foll way:

$ zip archive.zip libc.html User_guide.ps

Adding: libc.html (depressed 80%)

Adding: User_guide.ps (depressed 66%)\

46
Unix Commands
The unusual feature of this cmd is that it doesn’t overwrite an existing compressed file. If
archive.zip exists, files will either be updated or appended to the archive depending on
whether they already exist in the archive.

Recursive Compression (-r) for recursive behavior, zip uses the –r option. It descends
the tree structure in the same way tar does except that it also compress files. You can
easily compress your home dir in this way:

Cd ; zip -r sumit_home.zip

Using unzip files are restored with the unzip cmd, which in it’s simplest form, uses the
compressed filename as argument. Unzip does a non interactive restoration if it doesn’t
overwrite any existing files.

$ unzip archive.zip

Archive : archive.zip

Inflating : libc.html

Inflating : User_guide.ps

But if the uncompressed exist on disk, unzip makes sure that it’s doing the right thing by
seeking user confirmation:

Replace : libc.html? [y]es, [n]o, [A]ll, [N]one , [r]ename: y

You can respond with a y or n. you can also rename the file (r) to prevent overwriting or
direct unzip to perform the decompression on the remaining files non interactively (A).

Basic Files Commands(Accessing permissions on File)

1) Chmod :-

The external chmod command allows you to change the modes of a file or directory. The modes
are the access permissions controlling who can and cannot access the file or directory. File
modes control file attributes such as:

* Who can read from a file


* Who can write to a file
* Who can execute a file
* If a file allows you to assume its user ID during execution
* If a file allows you to assume its group ID during execution
* If a file is to remain in memory after execution
* If a file is to be locked while being accessed by a user

47
Unix Commands
The chmod allows you to change these attributes using:

* Absolute modes; all number arguments


* Symbolic modes; who strings, operators, and permission strings

The modes are classified into four categories. The first is the special modes. The last three are
the permissions for different sets of users:

* The owner of the file


* The group associated with the file
* All other users on the system

Following is the general format of the chmod command.

chmod [-options] [modes] [file/dir]


eg.. chmod [ -R ] absolute_mode file_list
chmod [ -R ] absolute_mode directory_list

chmod [ -R ] symbolic_mode file_list

chmod [ -R ] symbolic_mode directory_list

The following list describes the options that are used to control how chmod functions.

absolute_mode A three- or four-digit octal number describing the permissions. See the
following section on Absolute Modes.
symbolic_mode A string made up of three parts describing the permissions. The first part
is the "who string"; who is affected. The second is an "operator string";
add, remove, or absolutely assign permissions. The third is the
"permission string"; what are the permissions for the file or directory. See
the following section on Symbolic Modes.
-R Forces chmod to recursively descend the directory trees listed, changing
the group ID of files and directories. If a symbolic link is encountered, its
group ID is changed but it is not traversed.

The following list describes the arguments that may be passed to the chmod command.

file_list One or more files you want to give new modes.


directory_list One or more directories you want to give new modes.

The chmod command changes which users can read, write, and execute a file. The modes are
separated into four classes:

special Special permissions

48
Unix Commands
user The owner of the file or directory
group The users in the group that the file is associated
other All other users on the system

Each class of users has a set of modes controlling their access permissions.

The owner and super-user are the only people who can change the permissions of a file or
directory. To set the set-group-ID the file must have the same group ID as your current group ID.

You can use the chmod command to allow or deny access to a file or directory. By removing
read and write permissions for other users, you deny all users not in your group access to the file.
If you removed the read and write permissions from the group permissions, then only you could
access the data. In some cases you may want to remove your write permissions so you cannot
accidentally remove or overwrite the file.

Using the chmod command to set the execute permissions allows you to execute a file that
contains a shell script. You can also set the permission to l (lowercase L) for file locking. Then
only one program or user can access the file at any given time.

The absolute mode is used to set all modes at once. It is generally used by programmers that like
short syntax. The symbolic mode is easier to understand and remember. It is also more useful for
adding and removing only one or two specific modes.

 The cmd can be used in 2 ways:


o In a relative manner by specifying the changes to the current permission.
o In a absolute manner by specifying the final permission

1 )relative permissions(Symbolic):-

The symbolic mode consists of three parts. They are:

who string Who is affected (user, group or other)


operator What actions are to be taken (add, remove, or absolute)
permissions The permissions to add, remove, or absolute

The general format is:

chmod [ who_string ][ operator ][ permissions ] file_list


chmod [ who_string ][ operator ][ permissions ] directory_list

For example, the following command removes the write permission for all other users:

chmod o-w file

49
Unix Commands
The o refers to other users, the - implies remove, and w is for write permission. No spaces are
allowed in the symbolic mode strings.

Who string The who string controls which set of permissions are changed by the chmod
command. Any combination of the following letters can be used for the who string:

u The user (owner) of the file or directory


g The users in the group that the file is associated
o All other users on the system
a All of the above (same as "ugo"). All user classes.
If no who string is used, then the a is assumed. All user classes are affected.

Operators The operator controls what effect the permission strings will have on the
permissions of the files or directories. The possible operators are:

- Remove the specified permissions from the file or directory.


+ Add the specified permissions to the file or directory.
= Assign the absolute permissions as specified. Permissions not specified are removed.

The = operator assigns the given permissions. It is the same as performing a chmod 000 file or a
chmod a-rwx file, then performing the chmod to add the permissions specified after the =
operator. For example, if you had a file with the following permissions:

rwxr--- - 1 mylogin ts 5 Feb 2 afile

and you typed

chmod a=rx

the file permissions would change to

r-xr-xr-x 1 mylogin ts 5 Feb 2 afile

Permission String The permission string contains the permissions you want to add or remove
from the current permissions. You can combine the following letters to create the permission
string:
R Read permission
T Sticky bit, hold text in memory until space is needed
w Write permission
x Execute permission
u Indicate that permission is to be taken away from the current user
g Indicate that permission is to be taken away from the current group

50
Unix Commands
o Indicate that permission is to be taken away from the current others

Multiple symbolic modes can be used on the same command line. Separate each set of symbolic
modes with commas (,). For example,

chmod o+r,g-w myfile

would add read access for other users and remove write permission for group members.

More than one operator and permission sequence may be used for each who string. For instance,

chmod g+r-w myfile

would add read access for members of the group and remove write permissions.

You can remove all permissions by using the = operator and no permission string. For example,

chmod = myfile

removes all permissions for all users.

2 )Absolute permiison(octol):-

The absolute mode is a three- or four-digit octal number. Each position of the number equates to
a special meaning or a class of users. Absolute modes are a shorthand for changing permissions.
Therefore, they are terse and more difficult to remember and use.

The first digit is not required unless you wish to change the special modes. Thus you are allowed
to use a three-digit number when you are only changing file permissions relating to reading,
writing, and executing. The following list relates each position to what it does.

X000 Special meaning


0X00 Modes for the user class
00X0 Modes for the group class
000X Modes for the other class

To obtain the set of permissions desired, add up the numbers for a given class. For example, if
you want read and write permissions, you would add 4 (read) and 2 (write) to get 6 (read, write).

Octal(mask) permissions Dir permission Significance(dir) File permission

(default 777) (Default 666)


0 --- 0 (none) No permission 0(none)
1 --x 1(execute) Executable only 0(none)
2 -w- 2(write) Write only 2(write)

51
Unix Commands
3 -wx 3(write/execute) Write and 2(write)
execute
4 r-- 4(read) Read only 4(read)
5 r-x 5(read/execute) Read and execute 4(read)
6 Rw- 6(read/write) Read and write 6(read/write)
7 rwx 7(r/w/x) Read, write and 6(read/write)
execute

The above table shows that how mask is used to create the default permission.

* umask :-

The internal umask command masks your normal file modes, basically allowing you to have a
personally defined set of modes for all new files and directories you create. By using umask you
can:

* Set the modes to be used on all new files and directories created.
* Display the current masking for modes.

The normal default for a system is 022. This masks the write permission for the group users and
all other users. The result of umask 022 on a new file is permissions of 755, which is displayed
by ls -l as:

-rwxr-xr-x 1 mylogin ts 5 Jan 24 17:09 anewfile

Following is the general format of the umask command.

umask [ nnn ]

The following argument may be passed to the umask command.

nnn The umask value is set to nnn. This value must be an octal number. It is
subtracted from the standard mode of 777 column-by-column to define your
new file creation mode. You may think of the umask as the modes being
denied.
If you do not specify a value, the current umask value is displayed.

The umask command is usually used in the system's profile file or the user's own .profile. It
provides a means of controlling what modes are set for all users as defaults. You may decide you
want different default modes than are being used as a system default. If this is the situation, place
a umask command in your .profile to set your umask each time you log in.

52
Unix Commands
Ideally speaking, when you create a file Unix should ques you about what permissions you
would like to set for the file. That would be both time consuming and arduous. But file
permissions are at the heart of system security. So unix can’t afford to ignore them at any cost.

To overcome this problem unix has incorporated into itself what is called a “File creation
Masks”. This mask is system var called umask. It contains the permission that the user would
like to set, and everytime the user creates a file or a dir, permissions are assigned to it, depending
upon the value of the var.

The term mask implies that this var tells unix which permissions to mask or hide. Thus the
umask contains a val that tells unix which of the 3 permissions are to be denied, rather than
granted.

A user is permitted to set his own file creation masks, using this cmd.

Eg :- $ umask

022

The result of this cmd is 3 octal digits that refer to the permissions denied to the owner , group,
and others in the sys. Note that for the owner 0 or no permission is denied, whereas for both
group and others of write (2) permission is denied. the system-wide default permissions for a file
are 666 so that the file have permissions “ -rw- rw- rw”

Now the number that umask contains is subtracted from the default system-wide permission and
the resultant number is assigned to the created file as it’s permissions.

666

-022

644

Therefore the permissions assigned to the newly created file will be –rw-r—r—

the system-wide default permissions for a dir are 777.this implies that a dir bydefault is assigned
the permissions “ -rwx rwxrwx”

it may not make complete sense that a dir is assigned an execute permissions. After all it doesn’t
contain any executable code. But there is a special significance in the execute permissions to a
dir. In simple words if a dir doesn’t have an execute permission, you cannot enter into that dir
using cd cmd. This means that you can’t access any files in the dir.

777

-022

53
Unix Commands
755

Now with our umask set to 022, it is subtracted from the system-wide default for dirs and the
resultant permissions becomes drwxr-xr-x

**Changing owners and groups of files

The external chown command lets you change the owner of a file or directory. As a
normal user you can only change the ownership of files you already own. The super-user can
change the ownership of any file, regardless of who owns the file. You can specify a user name
or a user ID for the new owner.

The owner and optionally the group are changed with the change ownership (chown) cmd. The
new owner may be be a login name or a user is (UID). The group is optional. When it is used, it
is separated from the owner by a colon or a period. The group may be a group name or a group id
(GID), and the new owner must be a member of the group. The group does not have to be
changed when the owner is changed unless the new owner is not a member of the current group.

Only the current owner or a superuser may change the ownership or group. This means that once
the ownership is changed, the original owner cannot claim it back. Either the new owner or the
sys administrator must change it back. You change the file ownership and its associated group by
using the change ownership (chown) command.

Following is the general format of the chown command.

Chown [-options] newOwner:group file

chown [ R ] owner file_list


chown [ R ] owner directory_list

The following options may be used to change how chown functions.

-R Forces chmod to recursively descend the directory trees listed, changing the
group ID of files and directories. If a symbolic link is encountered, its group
ID is changed but it is not traversed.

The following arguments must be passed to the chown command.

owner The name of a user or the decimal user ID number specifying the new
owner.
file_list One or more files to change the ownership from your user ID to the
specified user ID of owner.
directory_list One or more directories to change the ownership from your user ID to the
specified user ID of owner.

54
Unix Commands
Change group (chgrp) command

The external chgrp command changes the group ID of a file or directory. To change the
group without changing the owner, you use the change group (chgrp) command.The group ID is
used to inform the system which group has group access permissions to a file. If you are a
member of the group that the group ID of a file is set to, then the group access permissions apply
to you when you try to access a file.

Each file on the system is identified by a group ID. Members of that group have access to
the file as specified by the group permissions. By using the chgrp command you can change
which group the access permissions affect.

Following is the general format of the chgrp command.

chgrp [-option] group list

chgrp [ -R ] group file list

chgrp [ -R ] group directory list

The following options may be used to control how chgrp functions.

-R Forces chgrp to recursively descend the directory trees listed, changing the group ID
of files and directories. If a symbolic link is encountered, its group ID is changed but
it is not traversed.

The following arguments may be passed to the chgrp command.

group The group you wish to permit access to your files or directories. You may
provide a group name or a group ID for group. For example, your group
name is "ts" and your group ID is "40."
file list One or more files to change the group ID so a different group can access the
files.
directory list One or more directories to change the group ID so a different group can
access the files.

The chgrp command is used to change the group ID of a file or directory. It allows you
to change which group may access your files. There may be certain sets of files that you need to
share with a documentation group. By using the chgrp command you can change the group ID
so users in the documentation group can access the files and directories.

55
Unix Commands
Usually the system administrator separates users into logical groups based on
functionality of departments within the company or project. The /etc/passwd file sets your group
ID to a number. The /etc/group file contains this number and its corresponding group name. The
file also contains a list of users who may be or become members of that group.

******************************************************************************

Tee cmd :-

The external tee command is used to write to the standard output and to a file simultaneously.
You place the tee command anywhere in a pipe command to divert a copy of the standard input
(of tee) to disk and another copy to your terminal. Thus its name is from the world of plumbing;
it allows one input and two outputs. The tee command actually allows multiple file copies. For
example,

sort unsorted | tee sorted | cut -c-20,41- | tee cutup | lp

sorts the data in the file unsorted; tee then sends a copy to the file sorted. The standard output of
tee is piped to cut which removes columns 21 through 40 and pipes it to another tee. The second
tee writes a copy to the file cutup and pipes a copy to lp for printing.

Following is the general format of the tee command.

tee [ -option ] file_list

The following options may be used to control how tee functions.

-a Appends the output to an existing file. If the file does not exist it will be
created. Normally an existing file would be overwritten.
-i Ignore interrupts. If you press the Delete key, tee ignores the interrupt signal
sent to it and continues processing.

The following argument may be passed to the tee command.

file_list One or more files where tee writes copies of the input.

You can use the tee command to execute a command interactively (in foreground) and save a
copy of the output on disk. The tee command can be placed anywhere in a pipe to check what the
output looks like at a certain point. Thus it lends itself to debugging pipe commands and
capturing output for later checking.

Eg..

$ who |tee /dev/tty a1 |wc –l >a1

56
Unix Commands
Hiren tty10 Sep 11 16:08

Hiren tty11 Sep 11 19:02

Fiter Cmd

Filters have the capability of reading standard i/p and writing to standard o/p .by default a
filter writes to standard o/p. it reads from standard i/p when used without a file name as argument
and from the file otherwise. The piping mechanism of the shell lets the standard o/p of 1 filter as
standard i/p of another this feature lets us design pipelines containing a series of filters.

1 ) pr (paginating files):-

The external pr command formats files for printing or displaying. It reads from
the standard input or from a list of files and writes to the standard output. The input is
reformatted according to specified options. The formatting is page and file oriented. Textual type
formatting, as done by troff, is not performed by pg. The output can be reformatted to multiple
columns, with or without headers and footers, indented, and double spaced, among various other
formats.

You can use pr to format files to your terminal screen or to a printer using the lp (lpr-BSD)
command. If you have a printer connected to the auxiliary port of your terminal, the -f option
comes in handy. You can enter your pr -f infile command and wait for pr to beep your terminal.
Then you can align your printer paper and activate the printer port on the terminal. Press Return
to have pr continue displaying your file.

Reformatting the data is useful. You may have a file that has tabs in it. Because the tabs are set at
every 8 spaces, the text extends off the end of your printer paper. To resolve the problem you can
use pr. For example,

pr -e4 infile

reduces each tab to four spaces instead of eight. This way you can squeeze more tab filled text on
a narrower piece of paper or screen.

You will find it helpful to use pr to send files to the system printer. By using pr you can
generate formatted listings of your program source code or various other text files. For example,

pr -n -e4 mysrc.c | lp -dlaser

formats the mysrc.c file with line numbers and tabs reduced to four spaces. The output of pr is
piped to the lp command with a destination of the laser printer.

Eg.. $ cat user

57
Unix Commands
barbara

david

$ pr -e4 user

Sep 10 16:49 2010 user Page 1

barbara

david

The following list describes the options and their arguments that may be used to control
how pr functions.

-d Double space the output. Blank lines at the top of the page are dropped.

-p Pauses before displaying the next page of output. The output must be to your
terminal screen. Your terminal's bell is sounded and pr waits for you to
press Return before displaying the next page.
-t Suppress the headers and trailers. The normal header has two blank lines: an
information line followed by two more blank lines. The information line
contains the Month, Day, Time, Year, Filename, and Page number. The
trailer consists of five blank lines. The -t option causes the -h option to be
ignored.

-n It display the line number.

-l page length is define.

-h Display header.

-o n offset lines by n spaces, increase left margin of page.

2)head (Beginning of file):-

The external head command displays the first few lines of a file. It displays
however many lines you specify as an option. If you do not specify the number of lines to
display, head defaults to ten.

The head command is useful for verifying what type of data is in a file. It can be used to
view the first few lines of an ASCII file to visually decide what data is contained in the file. You

58
Unix Commands
might consider head as a special version of the cat command, allowingç you to view the
beginning portion of the file.

The format of the head command follows.

head [ -n ] file

The following describes the option used to control how head functions.

-n The number of lines t display at the beginning of each file.

The following describes the argument that may be passed to the head command.

file_list One or more files to be displayed by head. If the -n is specified, it applies to all
files in the file_list.

If more than one file is specified on the command line, head precedes each file with a line like:

===> filename <===

If only one file is given on the command line, head does not inform you of the filename being
displayed.

Eg: $ head -5 a1 kk1

==> a1 <==

Hiren tty10 Sep 11 16:08

Hiren tty11 Sep 11 19:02

==> kk1 <==

tty10 Sep 11 16:08

3 )tail:-

The external tail command displays the last few lines of a file. It displays however many lines
you specify as an option. If you do not specify a number of lines, tail displays the last ten lines of
a file. Its cousin is the head command.

The tail command also provides an automatic displaying mode. You may have a process that
generates output to a log file and you want to watch the log as the process executes. By using the
59
Unix Commands
-f option, tail displays each new line in the file. This provides you the flexibility to watch the file
when you want to for however long you desire.

Syntax: tail [-options] inputfile

The general format of the tail command follows.

Option Code Description


Count from beginning +N Skips N-1 lines; copies rest
to end of the file.
Count from end -N Copies last N lines
Count by lines -l Counts by line(default)
Count by chars -c Count by Characters
Counts by blocks -b Counts by disk blocks
Reverse order -r Outputs in reverse order
(from bottom to top)
Follow -f Monitoring file growth

Many UNIX prgs constantly write to the system’s log file as long as they are running.
System admn need to monitor the growth of these files to view the latest msgs. For this
purpose tail offers the (-f) option.
The prompt doesn’t return even after the work is over. With this option, you have to use
the interrupt key to abort the process and exit to the shell.

Eg:- $ tail -3 eg //returns n+1 lines from the end of file.


i'm----
jhsgdja
fdshas
duyue$

$ tail +4 eg //skips n-1 lines and prints till the end-of -file
i'm am
i'm----
jhsgdja
fdshas
duyue$

$ tail -5c eg // extracts the 5 last chars from the file


Duyue
$ tail -2r eg // it extracts the 2 last lines of the file
duyuefdshas
jhsgdja
4) Cut

60
Unix Commands
The external cut command displays selected columns or fields from each line of a
file. A column is one character position. A field is a delimiter (tab) separated group of
characters.

The following functions and features are provided by cut:

* Displays columns of a table or file


* Displays fields of a table or file
* A field delimiter may be specified
* Suppress lines with no line delimiters

Following is the general format of the cut command.

cut -clist [ file_list ]


cut -flist [ -dchar ] [ -s ] [ file_list ]

The following list describes the options and their arguments that may be used to control
how cut functions.

-clist Display (cut) columns, specified in list, from the input data. No spaces are
allowed within the list. Multiple values must be comma (,) separated. The
list defines the exact columns to display. For example, the -c1,4,7 notation
displays columns 1, 4, and 7 of the input. The -c-10,50- format would
display columns 1 through 10 and 50 through end-of-line.
-flist Display (cut) fields, specified in list, from the input data. No spaces are
allowed within the list. Multiple values must be comma (,) separated. The
list defines the exact field to display. For example, -f1,4,7 would display
fields 1, 4, and 7. The -f2,4-6,8 would display fields 2, 4, 5, 6, and 8.
-dchar The character char is used as the field delimiter. The default delimiter is a
tab character. To use a character that has special meaning to the shell, you
must quote the character so the shell does not interpret it. For example, to
use a single space as a delimiter, type -d' '.
-s Suppress lines that do not contain a field delimiter. Normally these lines are
displayed.

The following argument may be passed to the cut command.

file_list One or more files to be cut and displayed.

Cut can be performed in 2 ways

1) Specifying the character position


2) Field Specification

Character Specification
61
Unix Commands
To specify the file in formatted with fixed format, we use the character option –c
followed by 1 or more column specifications. A column specifications can be 1 column or a
range of columns in the format n-m, where n is the start column and m is the end column.
Multiple columns are separated by comas.

$ cat > f2 //original file

aaaa bbbb ccccc ddddd eeeee

ffff gggg hhhhh iiiii jjjjj

kkkk llll mmmmm nnnnn ooooo

pppp qqqq rrrrr sssss ttttt

uuuu vvvv wwwww xxxxx yyyyy

zzzz

$ cut -c2,3-4 f2 //extracts only specified chars

aaa

fff

kkk

ppp

uuu

zzz

note that there is no space before and after the comma. If we provide a space in an option , the
option is terminated. In this case, cut would think that the 2nd column specification is a filename.

When we coded the cut cmd, we listed the columns for the name first followed by the columns
for the size. They are displayed in the order they are stored in the file. We can specify the
columns in any order; they are always cut in the order they are found in the file. If you overlap
the columns, cut will simply combines them into 1 column; no data are duplicated.

Eg: $ cut -c2-20,10-20 f2 //shows even id the fields are overlapped

aaa bbbb ccccc dddd

fff gggg hhhhh iiii

62
Unix Commands
kkk llll mmmmm nnnn

ppp qqqq rrrrr ssss

uuu vvvv wwwww xxxx

zzz

On the other hand if you specify the end column smaller than the starting column cut displays an
error msg.

$ cut -c2-20,10-2 f2 //shows the error msg for wrongly giving the chars

cut: invalid range for c/f option

Field Specification

To specify a field we use (-f) option. Like the character option, multiple fielda are
separated by commas with no space after the comma, consecutive field may be specified as a
range.

$ cut -f1-3,2-4 f2 //extracts only specified fields

aaaa bbbb ccccc ddddd

ffff gggg hhhhh iiiii

kkkk llll mmmmm nnnnn

pppp qqqq rrrrr sssss

uuuu vvvv wwwww xxxxx

zzzz
aaaa bbbb cccc dddd eeee
ffff gggg hhhh gggg iiii

The delimeter has a special meaning in unix, it must be enclosed within double quotes with --
-d option.
Eg:
$ cut -f2-4,1 -d"|" f3 //an eg for diff delimeter
aaaa|bbbb|ccccc|ddddd

63
Unix Commands
ffff|gggg|hhhhh|iiiii
kkkk|llll|mmmmm|nnnnn
pppp|qqqq|rrrrr|sssss
uuuu|vvvv|wwwww|xxxxx
zzzz
aaaa bbbb cccc dddd eeee
ffff gggg hhhh gggg iiii

Each option starts with a minus sign to identify it as an option. The delimeter may be
enclosed in either double or single quotes.
Thus –d”/” and -d’/’ both of them are correct
The (-s) option tells cut not to display any line that doesn’t have a delimeter.
Eg:
$ cut -f2-4,1 -d"|" -s f3 //not containing delimeter lines are suppressed
aaaa|bbbb|ccccc|ddddd
ffff|gggg|hhhhh|iiiii
kkkk|llll|mmmmm|nnnnn
pppp|qqqq|rrrrr|sssss
uuuu|vvvv|wwwww|xxxxx
5) paste :-

The external paste command combines files horizontally. If you have two files, it
would display the first file in the left column and the second file in the second column. The paste
command has various functions; they include:

* Combines files horizontally (side-by-side columns).


* Changes single-column input to multicolumn output.
* Removes all new-lines from all files creating one long line (serial output).

Following is the general format of the paste command.

Paste [-option] file_list

The following list describes the options and their arguments that may be used to control how
paste functions.
- The standard input. Causes paste to read one line from the
standard input.

-d Delimiter. Allows you to define what character you want to use to separate
columns of output. If you do not specify a list, the output columns are displayed
immediately next to each other.

If -d is not specified, a tab character separates all columns.

The list is zero or more characters used for output delimiters, replacing the default
tab character. The list must follow immediately after the -d option. If list consists

64
Unix Commands
of multiple characters, paste uses the first character to separate columns one and
two, the second character between columns two and three, and so on. If the list is
completely used and more columns exist, then the list is reused from the
beginning. Thus it is a circular delimiter list.

The list may contain any of the following standard C escape sequences:
\n A newline
\t A tab
\\ A backslash; since a backslash is a special character you must
escape it.

\0 No character at all. Same as -d without a list. But may be used in


multi- character list. Does not actually place a character on the
output.

You may have to quote the list to keep the shell from interpreting
certain characters. For example, to pass a backslash to paste you
would have to type -d"\\" or -d'\'.

-s Serial output. Allows you to combine all lines of each file into one line of
output. The -d option may be used to change the output delimiter. The last
character of output is always a new-line.

The following describes the argument that may be passed to the paste command.

One or more files read and displayed in the appropriate format.


file_list
The paste command is primarily used to paste files together horizontally. That is, each file is
placed in a column on the output. It may also be used to take multiple files for input and generate
one long serial line of output. A serial line of output has no new-line characters. Thus it is one
long line. Another use is to take a stream of input and generate multiple columns of output.

If the numbers of file is n then there should be n-1 delimiters specified with the paste
cmd.

$ cat >w1 // create a file w1


hi hello
$
$ cat >w2 // create a file w2
good morning
$
$ paste w1 w2 // simple paste the file
hi hello good morning
$ paste -d "|" w1 w2 // use “ | “ option for w1 and w2

65
Unix Commands
hi hello | good morning
$ paste -s w1 w2 // print serially
hi hello
good morning

6 ) sort :-
The external sort command sorts ASCII data. The input can be from files or the
standard input. The output can be a file or the standard output. If multiple input files are given,
the data from each file is merged during the sort.

You use the sort command to sort data alphabetically or numerically, in ascending or descending
order. You can sort based on entire lines, fields, or character columns. You can merge files using
sort and remove duplicate lines with it.

The sort command can read from the standard input and write to the standard output. Thus it can
be used in pipes or have its output redirected as desired. For example, sort can be used in the
following combinations of commands.

sort infile > outfile


sort infile | lp
who | sort
sort infile -o infile

In the first command sort reads and sorts infile and displays the result on standard output, which
has been redirected to outfile. In the second command sort reads and sorts infile and displays the
results on standard output, which is piped to the lp command. The third command pipes the
output of the who command to the input of the sort command. The sort then displays its output
on the standard output (your screen). In the last command sort reads from the file infile and
writes the sorted output to the file infile.

By default the sort command sorts based on entire lines. It compares the first character of two
lines. If the first character is the same, then the second character is compared, and so on until the
entire line is compared or the correct order is determined. Leading blanks (spaces and tabs) are
considered valid characters to compare. Thus a line beginning with a space precedes a line
beginning with the letter A. This is because the space is octal 040 in the ASCII sequence and an
A is octal 101.

Options Description
-t char Uses delimiter char to identify fields
-k n Sorts on nth fields
-k m,n Starts sort on mth field and ends sort on nth field
-k m.n Starts sort on nth column of mth fiels
-u Removes repeated lines
-n Sort numerically

66
Unix Commands
-r Reverse sort order
-f Folds lowercase to equivalent uppercase
-m list Merge sorted files
-c Checks if file is sorted
-o filename Places o/p in file name
-b Ignore leading space
-d Dictionary sort

Example of Sort

$ cat >sfile // Original file

5678 nilanjan d.g.m marketting

2365 nitin director personnel

9876 hitesh director production

2233 Hritik g.m sales

5423 Nitesh chairman admin

$ sort +1 -3 sfile // it skips 1st field and starts sorting from 2nd fields till 3rd field

2233 Hritik g.m sales

5423 Nitesh chairman admin

9876 hitesh director production

5678 nilanjan d.g.m marketting

2365 nitin director personnel

$ cat >s2 //original file

5678|Nilanjan|d.g.m|marketting

2365|nitin|director|personnel

9876|hitesh|director|production

2365|nitin|director|personnel

$ sort -t"|" s2 //sorting of the file having “|” as the delimeter

2365|nitin|director|personnel

67
Unix Commands
2365|nitin|director|personnel

5678|Nilanjan|d.g.m|marketting

9876|hitesh|director|production

$ sort -t"|" -u s2 //sorts only unique lines and removes the extra lines

2365|nitin|director|personnel

5678|nilanjan|d.g.m|marketting

9876|hitesh|director|production

$ sort -k3,4 sfile // Starts sort on 3rd field and ends sort on 4th field

5423 Nitesh chairman admin

5678 nilanjan d.g.m marketting

2365 nitin director personnel

9876 hitesh director production

2233 Hritik g.m sales

$ sort -k3.4 sfile // Starts sort on 3rd column of of 4th fields

5423 Nitesh chairman admin

5678 nilanjan d.g.m marketting

2233 Hritik g.m sales

2365 nitin director personnel

9876 hitesh director production

$ sort -n sfile // Sort numerically

2233 Hritik g.m sales

2365 nitin director personnel

5423 Nitesh chairman admin

5678 nilanjan d.g.m marketting

9876 hitesh director production

68
Unix Commands
$ sort -r sfile // Reverse sort order

9876 hitesh director production

5678 nilanjan d.g.m marketting

5423 Nitesh chairman admin

2365 nitin director personnel

2233 Hritik g.m sales

$ cat s1 // Original file

nilanjan|d.g.m|marketting

nitin|director|personnel

hitesh|director|production

Nitin|director|personnel

$ sort -f s1 // Folds lowercase “n” to equivalent uppercase “N”

hitesh|director|production

nilanjan|d.g.m|marketting

nitin|director|personnel

Nitin|director|personnel

$ sort -m mfile m1file //sorts file mfile(sfile) and s2(m1) and shows the o/p on
terminal

2233 Hritik g.m sales

2365 nitin director personnel

5423 Nitesh chairman admin

5678 nilanjan d.g.m marketting

9876 hitesh director production

Nitin|director|personnel

69
Unix Commands
hitesh|director|production

nilanjan|d.g.m|marketting

nitin|director|personnel

$ sort -c mfile //here the file mfile is sprted so it shows no msg

$ sort -c s10 //here the file is not sorted so it shows the line no where it first finds
the unsorted record

sort: disorder at record 1

$ sort s1 -o s9 //stores the o/p in s9 file

$ cat s9 //o/p of file s9

Nitin|director|personnel

hitesh|director|production

nilanjan|d.g.m|marketting

nitin|director|personnel

$ cat s9 //original file

Nitin|director|personnel

“tab” hitesh| director|production

nilanjan|d.g.m|marketting

“space” nitin|director|personnel

$ sort -b s9 //sorted file

hitesh| director|production

nitin|director|personnel

Nitin|director|personnel

nilanjan|d.g.m|marketing

$ sort -d sfile // Dictionary sort

70
Unix Commands
2233 Hritik g.m sales

2365 nitin director personnel

5423 Nitesh chairman admin

5678 nilanjan d.g.m marketting

9876 hitesh director production

7)uniq:-

The external uniq command reports duplicate lines in a sorted file. It reads in lines and
compares the previous line to the current line. Depending on the options specified on the
command line it may display only unique lines or one occurrence of repeated lines or both types
of lines. The default output is to display lines that only appear once and one copy of lines that
appear more than once.

It delete duplicate lines that are adjacent. If the lines are not adjacent it’s not deleted. The
compare whether line, field, or char , is to the end of the line.it is not possible to compare 1 field
in the middle of the line.

Following is the general format of the uniq command.

uniq [ -option][ input [ output ] ]

The following options are used to control how uniq functions.

-c Precedes each line with a count of the number of times it occurred in the input.
-d Deletes duplicate copies. Only one line out of a set of repeated lines is displayed.
-u Displays only lines not duplicated (uniq lines).

-f Skips leading fields and compares to end of line.

-s Skips leading charcters and compares to end of line.

The following arguments may be passed to the uniq command.

Input The name of the file containing the input data.


Output The name of the file to hold the output data. If no output file is specified, the
output is displayed on the standard output.
The input and output files must not be the same name. If they are, the
contents of the file are destroyed.

71
Unix Commands
If no input file is specified, uniq reads from the standard input and writes to
the standard output.
You cannot specify an output file without specifying an input file.

You can use uniq to reduce duplicate lines from a file. First the file must be sorted, then you can
remove the duplicate lines, reducing the size of the file.

It is also useful to filter out multiple blank lines from unsorted or sorted output of other
commands.

Example of Uniq cmd with option

$ cat ufile // the original book

5 completely duplicate lines

5 completely duplicate lines

5 completely duplicate lines

5 completely duplicate lines

5 completely duplicate lines

not a duplicate --next duplicate first 5

5 completely duplicate lines

last 3 fields duplicate: one two three

last 3 fields duplicate: one two three

last 3 fields duplicate: one two three

the next 3 lines are duplicate after char 5

abcde duplicate to end

fghij duplicate to end

klmno duplicate to end

$ uniq ufile //without any option

5 completely duplicate lines

not a duplicate --next duplicate first 5

72
Unix Commands
5 completely duplicate lines

last 3 fields duplicate: one two three

the next 3 lines are duplicate after char 5

abcde duplicate to end

fghij duplicate to end

klmno duplicate to end

$ uniq -u ufile // Select only unique lines

not a duplicate --next duplicate first 5

5 completely duplicate lines

the next 3 lines are duplicate after char 5

abcde duplicate to end

fghij duplicate to end

klmno duplicate to end

$ uniq -d ufile // select duplicate lines

5 completely duplicate lines

last 3 fields duplicate: one two three

$ uniq -c ufile // it count the duplicate lines.

5 5 completely duplicate lines

1 not a duplicate --next duplicate first 5

1 5 completely duplicate lines

3 last 3 fields duplicate: one two three

1 the next 3 lines are duplicate after char 5

1 abcde duplicate to end

1 fghij duplicate to end

1 klmno duplicate to end

73
Unix Commands
$ cat u1file //original file

5 completely duplicate dup lines

5 completely duplicate public lines

5 completely duplicate lines

5 complmetely duplicate hi lines

5 complhetely duplicate lines

not a duplicate --next duplicate first 5

5 completely duplicate lines

last 3 fields duplicate: one two three

last 3 fields duplicate: one two three

the next 3 lines are duplicate after char 5

abcdeeduplicate to end

fghij duplicate to end

$ uniq -s 8 u1file //skips 8-1 chars and compares upto the end of the line

5 completely duplicate dup lines

5 completely duplicate public lines

5 completely duplicate lines

5 complmetely duplicate hi lines

5 complhetely duplicate lines

not a duplicate --next duplicate first 5

5 completely duplicate lines

last 3 fields duplicate: one two three

the next 3 lines are duplicate after char 5

abcdeeduplicate to end

$ uniq -f 5 u1file //skips the 5-1 fields and compares upto the end of the line

74
Unix Commands
5 completely duplicate dup lines

not a duplicate --next duplicate first 5

5 completely duplicate lines

last 3 fields duplicate: one two three

the next 3 lines are duplicate after char 5

abcdeeduplicate to end

75

You might also like