Unit-I Directory Commands 1. The PWD Command
Unit-I Directory Commands 1. The PWD Command
Unit-I Directory Commands 1. The PWD Command
Directory Commands
$ pwd
/usr/kumar
$cd progs
$pwd
/usr/kumar/progs
$_
Though pwddisplays the absolute pathname, cd doesn't need to use one. The command cd progs
here means that you should change your sub-directory to progs (under the current directory).
Using an absolute pathname causes no harm either; user cd/usr/kumar/progs for the same
effect.
When you need to switch to the /bin directory where most of the commonly used UNIX
commands are kept, then you should use the absolute pathname:
$ pwd
/usr/kumar/progs
1
7 cd /bin
$ pwd
/bin
$_
$ pwd
/usr/kumar/progs
$ cd
$ pwd
/usr/kumar
$_
This create three sub-directories-pis, and two sub-directories in the just created sub-directory pis.
The order of specifying the arguments is important: you obviously can't create a sub-directory
before creation of its parent directory. For instance, you can't enter.
The pis directory will still be created spite of the terse message from the system about its failure
to create the sub-directories progs and data.
Sometimes, the system refuses to create a directory:
$ mkdir test
mkdir: can't make directory test
$_
2
This can happen when the directory test already exists, or the user doesn't have adequate
authorisaction to create a directory. This will be considered in some details while dealing with
file permissions.
Notice that when you delete sub-directories, as well as their parent directory (pis, this case), the
logic to be applied will have to b the reverse of the one used in creating directory with the mkdir
command. The following sequence is invalid:
This error message leads to two important rules that you should remember while deleting
directories. You can't delete a directory unless it is empty. In this case the pis directory couldn't
be removed because of the existence of the sub-directories progs and data under it. Even though
the system flashed the error message, it silently deleted the two sub-directories progs and data.
You now delete the pis directory using the same command but with a single argument:
$ rmdir pis
$_
The rm command, used with the –r can also be used to remove directories. The rmdir command
will first remove the contents of the directory, and then remove the directory itself.
The other important rule is that you can't remove a sub-directory unless you are placed in a
directory which is hierarchically above the one you have chosen to remove. For instance, you
can't remove the pis directory by executing the command from the pis directory itself. Try doing
that:
$ cd pis
$ pwd
/usr/kumar/pis
$ rmdir pis
rmdir: pis non-existent
$_
3
5. Listing out directory contents- the ls command:
The ls command allows you to see the contents of a directory, and to view basic
information (like size, ownership, and access permissions) about files and directories. The ls
command has numerous options. The ls command also accept one or more arguments. The
arguments can be directories or files.
Option Purpose
-x get multi-columnar output.
-r list files and subdirectories in reverse order.
-t list files and subdirectories with time order
-a list all files, including the normally hidden files.
-A list all files excluding . and ..
-c list files by inode modification time.
-i list inode for each file.
-l display permission, owner, size, modification time etc. alongwith file and
directory names.
-h Display names of hidden files also
-q Display file names having non-printable characters.
The ls command was used to obtain list of all files in the current directory, i.e. /usr/kumar. Run it
once again to have a look at the files now:
$ ls
chap01
chap02
dept.lst
desig.lst
emp1.lst
emp2.lst
genie.sh
helpdir
prggen.sh
progs
spcgen.sh
user.lst
$_
What you see here is a list of filenames arranged in ASCII collating sequence, with one filename
in each line. The command is often invoked to check whether a particular file is available.
However, when you have several files, it is better to use an option (i.e. a letter produced by a –
sign and following the command) with ls so that the filenames are displayed in multiple columns.
The –x option produces a multi-columnar output:
$ ls –x
chap01 chap02 dept.lst desig.lst emp1.lst emp2.lst
genie.sh helpdir prggen.sh progs spcgen.sh user.lst
$_
4
A similar output is displayed in XENIX when the lc command is used. The display in either case
shows only the filenames, and is so convenient, that many people have customized the command
to display in this format by default (i.e. when used without options). It doesn’t. however, show
the file attributes, nor does it indicate how many of them, if any, are directory or device files. To
identify directories and executable files, the –F option should be used. Since UNIX permits the
use of more then one option with a command (provided it supports multiple options), the –x and
–F options can be clubbe3d together to produce a multi-columnar output:
$ ls –F –x
chap01 chap02 dept.lst desig.lst emp1.lst emp2.lst
genie.sh* helpdir/ prggen.sh* progs/ spcgen.sh* user.lst
$_
Ex. Find out all the directories directly under the root directory.
Note the use of two symbols that tag some of the filenames. The * indicates that the file contains
executable code, while the / refers to a directory. You can now identify the two sub-directories in
the current directory; helpdir and progs.
Example:
To rename the file chap01 o man0, you should use
$ mv chap01 man01
$
If the destination file doesn’t exist it will be created. Unlike MSDOS, however, mv overwritten
the destination file if it exists. So be careful again.
Like cp, a group of files can be moved, but only to a directory. The following command
moves the files chap01, chap02 and chap03 to the progs directory. (This feature is not available
in MSDOS). There is one important distinction. However, with the cp command. mv can be used
to rename a directory, provided that both source and target directories have same parent. The
command
$ mv pis perdir
$
5
renames the directory pis to perdir.
File Commands
Ctrl + d
After pressing the Enter key, you will be prompted to enter the contents of the file. Type the
required data and press ctrl +d keys to terminate the command line.
The above command will display the contents of the two files in different rows. Use the
cat command to create and display the contents of the files.
6
2. Copying A File – The cp Command
The cp (copy) command copies a file or a group of files. Similar to the COPY command
of MSDOS, cp creates an exact image of the file on the disk with a different name. The syntax
requires atleast two file names to be specified in the command line. When both files are ordinary
files, then the first is copied to the second. To copy the chap01 to unit1, you have to write the
following command.
$ cp chap01 unit1
If the destination doesn’t exit, it will first be created before copying takes place. If not, it will
simply be overwritten. So be careful when you choose destination filename. Just check with an ls
command whether the file is exist or not. The –i is the (interactive) option, used with cp, warns
the user before overwritten the destination file. If the unit1 exists, then you get a different
response with the latest release:
$ cp –i chap01 unit1
cp: overwrite unit1? Y
$
A y at this prompt overwrites the file, while any other response (including n) terminates the
process.
It is now possible to copy an entire directory structure using the –r (recursive) option. The
following command copies all files and sub-directories in progs to newprogs:
$ cp –r progs newprogs
Since the process is recursive and copies all the files resident in the sub-directories.
$ rm progs/chap01 progs/chap02
$
You may sometimes require to delete all the files of a directory as a part of cleaning-up
operation. Unix System uses certain special characters which can be used to frame a pattern for
matching for more than one file. One of the characters you will be using is the *(asterisk), which
is interpreted to include all files in the current directory. Using this symbol, you can easily delete
all the files in this directory:
7
$ rm*
The rm is invoked with options. The –i (interactive) option makes the command prompt the user
with each filename and a ?, before act on it:
If you press a "y" after this message, then the file will be deleted. This process will be repeated
till all the files in the list are displayed. A "y" removes the file any other response leaves the file
undeleted.
When used with the –r option, rm performs a deadly recursive search for all sub-directories and
files within these sub-directories, and then deletes all these files (as well as the sub-
directives!).rm will not normally remove directories, but when used with this option, it will.
$ rm –r *
$
rm won't delete any file if it is write protected, but may prompt you with its mode (in octal)
before it decides to delete them. The –f option overrides this protection also. If will force
removal even if the files are write protected.
$ rm –r –f
8
7. Comparing two files – The cmp command
This command is used to compare two files are identical in all respect so that one of them
can be deleted. The cmp (compare) command is used to achieve this task. When used without
options, it uses two filenames as argument, and displays the differences on the terminal:
$ cmp chap01 chap02
chap01 chap02 differ: char 9, line 1
$
The two files are compared byte by byte, and the location of the first mismatch is echoed to the
screen. cmp, when invoked without options, doesn’t bother about possible subsequent dispatches,
but simply aborts with the message shown above. In this case, the first mismatch was noticed in
the ninth character of the first line.
The two files are identical, then cmp displays no message, but simply returns the $ prompt. This
follows the UNIX tradition of quiet behaviour. You can try it out with two copies of the same
file:
$cmp chap01 chap02
$
The –l (list) options gives a detailed list of the byte number and the differing bytes in octal for
each character that differs in both the files. Before comparing the two files note1 and note2:
$ cat note1
abcd
xyz
$
$cat note2
abed
wxy
$
9
>barun dasgupta and this line
2c4 change line2 of first file
<chanchal singhavi Replacing this line
-- with
>lalit chowdury this line
4d5 Delete line 4 of first file
<sumit chakrobarty containing this line
diff uses certain symbols and instructions to indicate the changes that are required to make two
files identical. You should understand these instructions as they are used by the sed command,
one of the most powerful commands on the system. Each instruction uses an address combined
with an action that is applied to the first file. 0a1,2 means appending two lines after line 0, which
becomes lines1 and 2 in the second file. 2c4 changes line 2 which is line 4 the second file.
Example
$grep sales emp.lst
10
10. File Permissions – The chmod command
Issue the ls-l command to list some files of the current directory.
$ ls-l charp02 dept.lst dateval.sh
The first column contains all details of the permissions of a file. Observe that these permissions
take the general form
-rwxrwxrwx
Unix follows a three-tired file protection system, which determines the access rights that
you have for a file. Each tier represent a category, and consists of a string rs, ws and xs to
represent three types of permission. r indicates read permission, i.e. the file can be read by using,
cat command. w indicates write permission, i.e. you direct some output to it. x indicates execute
permission, i.e the file can be executed as a program. If any of these permissions don’t apply to a
specific category, then a -(hyphen) occupies the respective slot. You cant read, write or execute
every file; the authority to do that is entirely determined by the category of user you belong to,
and the permissions applicable for that category. For example, if the file chap01 doesn’t have any
permission for any category, then this expression takes this form
----------
If you try to read this file, using cat command, the system notifies its failure:
$cat chap01
cat: cant open chap01
$_
This is an important feature provided by UNIX in the sense that it write –protects a file from all
except the owner of the file, though by default, all the users have read access. By default, a file
doesn’t have executable permission. So how does one execute such a file? To do that, the
permission of the file need to be changed. This done with the chmod(change mode) command.
The chmod command is used to set the three permission for all the three categories of users of a
file. It can only used by the owner of the file and uses the following syntax:
11
The command assigns (+) executable (x) permission for the user (u), other permission remain
unchanged.
Other examples:
1. $ chmod + r note
2. $ chmod og-x note
3. $ chmod o-rwx note
$ pr dept.lst
01 | account | 6213
02 | admin | 5423
03 | marketing | 6521
04 | personnel | 2365
05 | production | 9876
06 | sales | 1006
<.. blnak lines ..>
$_
pr adds five lines of margin at the top and five at the bottom. Since it uses an entire page for
printing, the lower portion of the page has not been shown in the examples. Of the five lines at
the top, one is reserved for header information. The headers shown the date and time of the last
modification of the file, along with the filename and page number.
12
-h stg Sets header for every page to string stg
-n number lines in output
-on Offsets output by n characters
-d double spaces output
-t eliminates header, footers and margins
$ head emp.lst
You can specify a linecount and display, say the first three lines of the file. Use the - symbol
followed by a numeric argument:
$ head -3 emp.lst
$ tail -3 emp.lst
13
f- selects the specified fields
d – delimiter of the fields ( default being tab space)
Examples
1. Displaying 2 & 3 fields of file pers_dat.dat where delimiters for the field are ";" .
$ cut –d ";" –f 2,3 pers_dat.dat
2. Display characters 6 to 12 both inclusive from file pers_dat.dat
$ cut –c 6-12 pers_dat.dat
3. Display the list of directory files we use cut as a filters to cut the first characters of the
output pf ls-l command which gives the file type. We use grep command to search the
letter 'd' which indicates directory file.
$ ls – l | cut –c | grep "d"
Syntax:
Paste [options] <file1><file2>
Example:
F_Name L_Name
Chetan Shrivastava
Rakesh Sharma
Ram Pande
Rima Lagu
Madhuri Joshi
Raj Sinha
To display the names, together as first name and last name. We give the following
command
$ paste F_Name L_Name
We get the output as follows
Chetan Shrivastava
RakeshSharma
Ram Pande
Rima Lagu
Madhuri Joshi
Raj Sinha
6. Ordering A File – The sort Command
This command is used for sorting the data and give the output on the standard output
device, unless specified. Sort performs its usual functions but it has couple of unique features.
By default sort reorders lines in ASCII collating sequence –whitespace first, then numerical,
uppercase letters and finally lowercase letters. This default sorting sequence can be altered by
using certain options.
The basic Syntax is
14
Sort [-options] [+pos] [-outputfile] [filename]
Options
n – sort on the first numeric field
r –reverse the default order of sort default means ascending order.
d –sorting on dictionary order that is only letters, digits and blanks
u – for eliminating duplicates lines in the sorted output.
t – to specify the field separator character
o – storing the sorted output in a file.
Example: -
$ sort shortlist
7. pg command
This command is quite similar to the more command and is used for displaying the screen
full contents at a time.
Syntax:
pg <filename>
Example:
ls | pg – Will display list of screenful of files with a: colon prompt at end, where one can specify
options as follows
n – to display next file
q –to exit and return to prompt
p – to display previous file
Options of wc:
15
Example:
$ cat infile
I am the wc command
I count characters, words and lines
With options I can also make a selective count.
$_
There are 3 lines in a text in this file, explaining briefly what the w command is all about. You
can now use it without options to make a "word count" of the data in the file.
1. $ wc infile
3 20 103 infile
2. $ wc –l infile
3 infile
3. $ wc –w infile
20 infile
4. wc –c infile
103 infile
Pipeline
The pipe (|) operator is used to indicate to the shell to take input from another command
or give output to another command or give output to another command. For example, suppose
you want to count the number of files in your directory sales. For this, one method is to first list
all the files using ls command and then manually count the number.
Anther method is to save the output of ls into a file (using <) and then count the number
of lines in the file using wc-l command. This method, through it works, requires an intermediate
file.
The third and the best method is to connect the two commands, so that one can take input
from the other. This is can be done using the pipe (|) operator as follows
$ ls sales | wc – l
Here the output of ls has been passed directly to the input of wc. That is, ls is said to be
piped to wc.
These are special characters that are recognized by the shell. For selective display of files we use
meta character or wild card. It is also called as Wild card characters or (pattern matching).
1. *
This is a ‘wildcard’, it matches any string of zero or more characters, except a leading ‘.’
An example of its use
$ ls *.mod
This will list all the files in the current directory that end with a. mod
$ ls ca*
16
This will list all the files that commence with the letter ‘ca’ and have zero or more
characters afterwards.
2. ?
This will match any single character An example of its use is
$ ls tut?.m
This will find files such as tut1.m, tut2.m, etc.
$ ls *.[ch]
This will list all files in the current directory that end in either .c or .h.
3. >
Redirect standard output (the terminal) to a file. An example of its use is:
$ echo “Hello world” > hello.txt
$ cat hello.txt
Hello World
4. >>
Appends standard output to a file. An example of its use is:
$ echo “Hello again”>>hello.txt
$ cat hello.txt
Hello world
Hello again
5. <
Take standard input form a file. An example of its use is:
$ main bruce < myfile.mod
This will mail the file myfile.mod to the user bruce.
6. |
This is the pipe character. P1|P2 connects standard output of P1 to standard input of P2.
An example of its use is:
$ cat poem.txt | lpr –Psoup
This will print the contents of the file poem.txt to the printer called soup.
$ cat duckpond | tr ’ ’ ’\n’ | grep –I frog | wc – l
This will count the number of frogs in the duckpond file.
7. ;
P1;P2 executes P1 and then P2.
$ cd Temp ; lpr –Psoup file.txt
This will change your working directory to Temp and print the file file.txt in that directory to the
printer called soup.
8. &
17
This starts a process in the background. P1 & will cause P1 to start running, and return
you to the shell you were typing at, while P1 keeps going. This useful for programs which starts
up their own xwindow.
9. &&
In P1 && P2 succeeds, then P2 is executed. This is like a logical and: both P1 and P2
have to succeed for the compound statement to succeed.
$ latex file && dvips file
If the file latex command succeeds, then dvips will be run.
10. ||
In P1 || P2, if P1 fails, then P2 executed. This is like a logical or: only one of P1 and P2 have to
succeed for the compound statement to succeed.
$ ./assign1 || echo “bugger”
This program assign1 (in the current directory) is run. If it fails. Then a helpful error message is
printed.
Vi Editor
One of the most widely used full screen text editor in Unix is ‘vi’. vi (visual) is the most
powerful text editor available in almost all UNIX and LINUX system. The user is given one
screen fill of data at any instant for modification. The undisplayed part of file, if it all needed,
can be had for editing by scrolling till the part that is to be edited is displayed on the screen.
The format of the command to invoke the editor is:
Vi [<options>] [<file name>…]
The editor can be supplied with one or more than one file to edit. When no file name has been
given, it has to be done so at the time when the text being edited is to be written on to the disk.
1} Command Mode
This is the mode where the editor is ready to accept any of the user response after being
activated and the screen filled with text for modification. In this mod the user can manipulate the
cursor position, insert, delete, append or change characters or line of text. Command mode is the
mode where you will be giving commands to the vi editor. When you invoke vi, this is the mode
where you will be placed initially.
18
command i in the command mode. You will now get placed in the input mode and you can
perform the intended task. No commands can be given while you are in the input mode. For
example, if you type ‘a’ here it will not be interpreted as an ‘append’ command, but as character
‘a’ to be inserted in the file. To move back to command mode press Esc Key.
Some commands are. .
h – Move one character to the left
l – Move one character to the right
k – Move up
j – Move down
….
3} The ex mode
vi uses the ZZ command to save and quit the editor. It doesn’t have any other command
to do that. These features are adequately handled by ex, and to avail yourself of them you have to
use the ex mode, sometimes referred to as last line mode. These mode should be invoked for
performing those functions which either vi cant perform, or which can be handled by ex in an
easier manner.
You can switch from the command mode to the ex mode by pressing a :, which appears
as the ex prompt in the bottom line. You are now free to enter any ex command at this prompt.
Command Used to
w save the changes you have made to the file
q quit vi without saving changes
wq save and quit
q! force quit if ‘q’ does not work
19