Unix Command
Unix Command
Unix Cmds
The file system cmds:--
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
1
Unix Commands
$ pwd
/home/john
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.
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.
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.
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:
If the name of the dir not provided it will display the content of the working dir..
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:-
$ 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/
Eg:- $ ls -R
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
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
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
Eg: $ ls -i
-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
Eg: - $ ls -p
Eg:- $ ls -r
-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
Here if we only apply the ls cmd then the o/p appears as follows.
$ ls
-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
$ 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.
- 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:
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.
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.
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.
date [ -u ] [ +format ]
eg:
$ date
Or
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
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 %%.
%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:
COMMAND FORMAT
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: _
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
\c writes the output, but does NOT terminate it with a new-line. Must be last.
\n produces a new-line.
\t produces a 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.
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
%s - string
%d -Decimal integer
%o -Octal integer
%x -Hexadecimal integer
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 ]
-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 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.
$ pwd
/home/hello/sem5
$ pwd
/home/hello/sem5
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.
passwd [ 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.
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.
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.
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.
Eg..
i) $ who
iii) $who am i
The who am I cmd identifies the invoking user and lists the user name , terminal line, and the
date and time of log-in.
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
EG:- $ tty
o/p-> /dev/tty10
$ echo $?
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.
Eg:- $ stty
kill = ^U;
20
Unix Commands
swtch = ^”; susp = ^Z;
-parenb
-ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr -iuclc -ixany -ixo
ff -imaxbel -iexten
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
-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.
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
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.
$ 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
-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.
-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$
-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:
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:
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
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..
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."
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
Eg..
$ echo rm –r f* //it wil display the list of files that will be removed by that cmd..
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:
-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.
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.
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.
v- to invoke vi editor.
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.
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
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 *
31
Unix Commands
copy1: directory, searchable
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.
wc [ - option ] [ file_list ]
-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 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.
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.
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.
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.
i m ^g
$ od -b k1
0000007
$ od -c k1
0000000 i m ^ g \n
0000007
$ od -bc k1
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.
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:
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.
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.
- 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.
$ cat log
name line
user1 ttyla
user2 tty2c
accell tty2d
$ cat log-user
name line
user1 ttyla
user2 tty2c
infress tty2d
If 2 files are identical, cmp displays no message but simply returns the prompt.
Eg..
$ cp log log1
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
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.
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
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.
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.
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,
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.
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.
41
Unix Commands
2,4c3 // change line 2 to 4 from file1
< david
< george
< jill
---
6d4 // delete line 6 from user file. B’coz it diifers from mgnt by 4 characters (i.e. tina)
< tina
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 .
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.
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.
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 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.
-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.
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:
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:
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.
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:
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:
To view the content of the archive, use the –t options. It doesn’t extract
files but simply shows their attributes in a form :
1 file, 4 blocks
.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:
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:
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).
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:
47
Unix Commands
The chmod allows you to change these attributes using:
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 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.
The chmod command changes which users can read, write, and execute a file. The modes are
separated into four classes:
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.
1 )relative permissions(Symbolic):-
For example, the following command removes the write permission for all other users:
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:
Operators The operator controls what effect the permission strings will have on the
permissions of the files or directories. The possible operators are:
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:
chmod a=rx
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,
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,
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
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.
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).
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:
umask [ nnn ]
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
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.
-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.
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.
-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.
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,
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.
-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.
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..
56
Unix Commands
Hiren tty10 Sep 11 16:08
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,
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.
57
Unix Commands
barbara
david
$ pr -e4 user
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.
-h Display header.
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.
head [ -n ] file
The following describes the option used to control how head functions.
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:
If only one file is given on the command line, head does not inform you of the filename being
displayed.
==> a1 <==
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.
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.
$ tail +4 eg //skips n-1 lines and prints till the end-of -file
i'm am
i'm----
jhsgdja
fdshas
duyue$
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 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.
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.
zzzz
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.
62
Unix Commands
kkk llll mmmmm nnnn
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
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.
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:
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.
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.
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.
If the numbers of file is n then there should be n-1 delimiters specified with the paste
cmd.
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.
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
$ sort +1 -3 sfile // it skips 1st field and starts sorting from 2nd fields till 3rd field
5678|Nilanjan|d.g.m|marketting
2365|nitin|director|personnel
9876|hitesh|director|production
2365|nitin|director|personnel
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
68
Unix Commands
$ sort -r sfile // Reverse sort order
nilanjan|d.g.m|marketting
nitin|director|personnel
hitesh|director|production
Nitin|director|personnel
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
Nitin|director|personnel
69
Unix Commands
hitesh|director|production
nilanjan|d.g.m|marketting
nitin|director|personnel
$ sort -c s10 //here the file is not sorted so it shows the line no where it first finds
the unsorted record
Nitin|director|personnel
hitesh|director|production
nilanjan|d.g.m|marketting
nitin|director|personnel
Nitin|director|personnel
nilanjan|d.g.m|marketting
“space” nitin|director|personnel
hitesh| director|production
nitin|director|personnel
Nitin|director|personnel
nilanjan|d.g.m|marketing
70
Unix Commands
2233 Hritik g.m sales
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.
-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).
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.
72
Unix Commands
5 completely duplicate lines
73
Unix Commands
$ cat u1file //original file
abcdeeduplicate to end
$ uniq -s 8 u1file //skips 8-1 chars and compares upto the end of the line
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
abcdeeduplicate to end
75