Unix and Shell Programming: 1. Overview of Operating System
Unix and Shell Programming: 1. Overview of Operating System
5. Shell Programming
The Shell – The Shell’s Interpretive cycle, Shell offerings, Pattern Matching,
Redirection, Two special files, pipes, tee, command substitution, shell
variables.
Basic Shell Programming: Shell scripts, Making Scripts Interactive, Using
Command line arguments, exit and Exit status of a command, The logical
operators && and ||,the if conditional, using test and [ ] to evaluate
2
expressions, the case conditional, expr, $0, while, for, set and shift, the
here document, trap, debugging shell scripts with set –x.
Advanced shell programming- Shells and Subshells, export, Running script
in the current shell, let, arrays(korn and bash), String handling, Conditional
Parameter Substitution, Shell functions, eval, the exec statement.
6. Perl
Features of perl, chop(),variables and operators, String Handling function,
Specifying filenames in command line, $_,$.,Range operator, Lists and
arrays, foreach, split, join, dec2bin, grep, associate arrays, regular
expressions and substitution, file handling, file tests, subroutines.
Text Books
1. Unix concepts and applications – Sumitabha Das
2. Unix the Text book –Syed Mansoor Sarwar, Robert Koretsky,Syed Aqeel
Sarwar.
3. Unix Shell Programming – Yashavant Kanetkar
History of Unix
1969
First UNIX at Bell Labs
The MULTICS
Kernighan, Ritchie, Thompson
1970’s
Bell Labs makes UNIX freeware
Berkeley UNIX (BSD)
Bill Joy vi editor, C Shell
1980’s
System V release 4
TCP/IP
Sun Microsystems Solaris
Microsoft Xenix, SCO
MIT X-Windows
1990’s
GNU, LINUX
Stallman, Torvalds
kernal:-the kernal is the core of the operating system-a collection of routines mostly written in c.these
routines communicate with the hardware directly.it is that part of the unix system that is loaded into
3
memory when the system is booted.user progams(the applications) that need to communicate with the
hardware(like the hard disk or the terminal) use the services of the kernal,which performs the job on
the user’s behalf. These programs access the kernal through a set of functions called system calls.
kernal also manages the system’s memory, schedules processes, decides their priorities.
Shell:-it is actually the interface between the user and the kernal.even though there’s only one kernal
running on the system, there could be several shells in action-one for each user who is logged in.
System calls: these are the functions to communicate with the kernal.often the same system call can
access both a file and a device.these system calls are built into the kernal, and interaction through them
represents an efficient means of communication with the system.
Ans: the POSIX (Portable Operating System Interface for Computer Environments) standard refers to
a group of related standards for operating systems in general, but was based on UNIX because UNIX
was supposedly free from bias on account of its vendor-neutrality.two of the most –cited standards
4
from the POSIX family are known as POSIX.1 and POSIX.2.POSIX.1 specifies the c application
program interface-the system calls.POSIX.2 deals with the shell and utilities.
The second entity is the process, which is the name given to a file when it is executed as a
program.like files, processes also belong to a separate hierarchical tree structure.
6. Pattern matching
7. Programming Facility
The UNIX shell is also a programming language.It has all the necessary ingredients, like
control structures, loops and variables, that establish it as a powerful programming language in
its own right.these features are used to design shell scripts-programs that also include UNIX
commands in their syntax
8. Documentation
The principle on-line help facility available is the man command, which remains the most
important reference for commands and their configuration files.
The execution of this vanishes whatever was typed and the prompt and cursor are positioned at
the top-left corner of the screen.
$ exit
login:
The login: message confirms that the session has been terminated, thus making it available for
the next user.
Ans: the commands having independent existence in the /bin directory (or /usr/bin), are called as an
external command.
For ex: ls command is an external command
Echo isn’t an external command in the sense that, when we type echo, the shell won’t look in its
PATH to locate it (even if it is there in /bin).Rather, it will execute it from its own set of built-in
commands that are not stored as separate files.these built-in commands, of which echo is a member are
known as internal commands.
ans: unix offers an on-line help facility in the man command.A man page is divided into a number of
compulsory and optional sections.Every command doesn’t have all sections but the first three( NAME,
SYNOPSIS and DESCRIPTION) are generally seen in all man pages.
NAME presents a one-line introduction to the command.
SYNOPSIS shows the syntax used by the command and DESCRIPTION (often the largest section)
provides a detailed description.the SYNOPSIS follows certain conventions and rules which every user
must understand:
If a command argument is enclosed in rectangular brackets, then it is optional;
otherwise, the argument is required.
The ellipsis (a set of three dots) implies that there can be more instances of the
preceding word.
If there is a | character in any of these areas, it means that only one of the options
shown on either side of the pipe can be used.
All options used by the command are listed in the OPTIONS section.There’s a separate section EXIT
STATUS which lists possible error conditions and their numeric representation.
$ Cal 03 2003
March 2003
S M Tu W Th F S
7
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
to display a message
to evaluate shell variables
echo interprets certain strings known as escape sequences.
An escape sequence is generally a two character-string beginning with a \ (backslash).
printf:
The command in its simplest form can be used in the same way as echo:
$ Printf “No filename entered\n”
No filename entered
$ _
printf also accepts all escape sequences used by echo.printf uses many of the formats used by C’s
printf function.
%s string
%30s as above but printed in a space 30 characters wide
%d decimal integer
%6d as above but printed in a space 6 characters wide
%o octal integer
%x hexadecimal integer
%f floating point number
8
bc: bc belongs to a family of commands that expect input from the keyboard when used without an
rgument.key in the following arithmetic expression and then use [Ctrl-d] to quit bc:
$ bc
12 + 5
17
[Ctrl-d]
$ _
To enable floating-point computation, the sacle have to be set to the number of digits of precision
Scale=2
17/7
2.42
ibase=2
11001010
202 ;output in decimal-base 10
obase=2
14
1110
This command tells the filename of the terminal you are using
$tty
/dev/pts/10
The terminal filename is 10 resident in the pts directory.the directory in turn is under the /dev
directory. Tty is used in a shell script to control the behaviour of the script depending on the terminal it
is invoked from.
9
5. Explain date, uname, sttty, who, script commands with options and example
10
Ans: date: we can display the current date with the date command, which shows the date and time to
the nearest second:
$ Date
Tue Dec 10 18:52:26 IST 2002
$ date +%m
12
$ date +%h
Dec
Uname: the command displays certain features of the operating system running on your machine. By
default, it displays the name of the operating system:
$ uname
SunOS
The Current Release and Implementation Name (-r and –s): the –r option is used to find the version of
your operating system
$ uname -r
5.8
The implementation name of this operating system can be obtained with the –s option
$ uname -s
10
SunOS
The Machine Name (-n): if your machine is connected to a network, then it must have aname (called
hostname).-n option tells the hostname
$ uname -n
mercury
$ who
The first column shows the usernames (or user-id), the second column shows the device names of their
respective terminals, the third, fourth and fifth columns show the date and time of logging in.the last
column shows the machine name from where the user logged in.
(-H) option prints the column header.
To know the user who invoked the who command use the arguments am and I with who:
$ who am i
kumar pts/10 Aug 1 07:56 (pc123.heavens.com)
$ script
Script started, file is typescript
$ _
The prompt returns and all your keystrokes that you noe enter here get recorded in the file typescript.
Script –a
Ans: the file is a container of information or a sequenceof charactersunix treats directories and devices
as files as well.
11
Files can be divided into three categories
ordinary file:an ordinary file itself can be divided into two types:
.text file:a text file contains only printable characters.all C and Java program sources,
shell and per1 scripts are text files.
.binary file:a binary file contains both printable and unprintable characters that cover
the entire ASCII range. Most UNIX commands are binary files, and the object code and
excutables that you produce by compiling C programs are also binary files.
Pictures, sounds and video files are binary files as well.
Directory file:a directory contains no data, but keeps some details of the files and subdirectories
that it contains.
A directory file contains an enty for every file and subdirectory that it houses.each entry
has two components:
. The filename
.a unique identification number for the file or directory.
Device file:
Device filenames are generally found inside a single directory structure, /dev.it is
advantageous to treat devices as files as some of the commands used to access an ordinary
file also work with device files.the kernal identifies a device from its attributes and then
uses them to operate the device.
Ans: the file system in unix is a collection of all the related files (ordinary, directory and device files)
organized in a hierarchical structure.the implicit feature of every unix file system is that there is a top,
which serves as the reference point for all files.this top is called root and is represented by a /
(frontslash).root is actually a directory.
The root directory(/) has a number of subdirectories under it.these subdirectories, in turn , have more
subdirectories and other files under them.every file apart from the root,must have a parent,and it should
be possible to trace the ultimate parentage of a file to root.
7.explain the following commands with options and suitable example pwd,wc,cp,rm,more
10
$ pwd
/home/kumar
pwd displays the absolute pathname.
wc:wc command counts lines,words,and characters,depending on the options used. It takes one or
more filenames as its arguments, and displays a four-columnar output.
12
$ wc infile
3 20 103 infile
wc counts 3 lines,20 words and 103 characters.
wc offers three options to make a specific count.the –l option counts only the number of lines, while
the –w and –c options counts words and characters respectively:
$ wc -l infile
3 infile
$ wc -w infile
20 infile
$ wc -c infile
103 infile
when used with multiple filenames, wc produce a line for each file,as well as a total count.
cp: the cp command copies a file or a group of files.it creates an exact image of the file on disk with a
different name. the syntax requires at least two filename to be specified in the command line.
When both are ordinary files,the first is copied to the second
Cp chap01 until
If the destination file(until) doesn’t exist, it will first be created before copying takes place.
Interactive copying (-i): the –i option warns the user before overwriting the destination file.
$ cp -i chap01 until
Copying directory structure (-R): it’s possible to copy an entire directory structure with the –R option.
cp -R progs newprogs
rm: files can be deleted with rm .it can delete more than file with a single invocation.the following
command deletes the first three chapter of the book:
Interactive deletion (-i): the –i option makes the command ask the user for confirmation before
removing each file.
Recursive deletion (-r or –R): with the –r (or –R) option, rm performs a tree walk – a through recursive
search for all subdirectories and files within these subdirectories.at each step it deletes everything it
finds.
13
Forcing removal (-f): rm will prompt you for removal if a file is write-protected.the –f option overrides
this minor protection also.
More chap01
The contents of chap01 is displayed on the screen,one page at a time.at the bottom of the screen,you’ll
also see the filename and the percentage of the file that has been viewed.
--more—(17%)
to move forward one page,use f or spacebar & b to move back one page.10f can be used to scroll
forward by 10 pages & 30b for scrolling back 30 pages.
More has a repeat command, the dot that repeats the last command you used
Ans: ls command is used to list the names of the files available in the directory
$ ls -x
ls with –a option lists all hidden files all with the other files.
Ans: If the first character of a pathname is a /, the file‘s location must be determined with respect to
root. Such a pathname is called an absolute pathname.
The relative pathname uses either the current or parent directory as reference and specifies the path
relative to it.a relative pathnames uses one of these cryptic symbols:
. (a single dot)- This represents the current directory.
..(two dots)-this represents the parent directory.
Aruments are the additional words used along with the commands UNIX command use a filename as
argument so the command can take input from the file.
14
Options are special type of argument that’s mostly used with a – sign. For ex;
ls -l note
Ans: file command is used to determaine the type of file (regular, directory or device)
$ file archive.zip
archive.zip: ZIP archive
File recognizes text files, and can distinguish between shell programs,c source and object code.it also
identifies DOS executables,compressed files,PDF documents and even empty files.
HOME variable: home directory is created by the system when a user account is opened.the shell
variable HOME knows your current directory.the home directory is determined by the system
administrator at the time of opening a user account.
The UNIX file system allows the user to access other files not belonging to them and without
infringing on security. A file has a number of attributes (properties) that are stored in the inode. In this
chapter, we discuss,
ls command is used to obtain a list of all filenames in the current directory. The output in UNIX
lingo is often referred to as the listing. Sometimes we combine this option with other options for
displaying other attributes, or ordering the list in a different sequence. ls look up the file’s inode to
fetch its attributes. It lists seven attributes of all files in the current directory and they are:
The file type and its permissions are associated with each file. Links indicate the number of file
names maintained by the system. This does not mean that there are so many copies of the file. File is
15
created by the owner. Every user is attached to a group owner. File size in bytes is displayed. Last
modification time is the next field. If you change only the permissions or ownership of the file, the
modification time remains unchanged. In the last field, it displays the file name.
For example,
$ ls –l
total 72
-rw-r--r-- 1 kumar metal 19514 may 10 13:45 chap01
-rw-r--r-- 1 kumar metal 4174 may 10 15:01 chap02
-rw-rw-rw- 1 kumar metal 84 feb 12 12:30 dept.lst
-rw-r--r-- 1 kumar metal 9156 mar 12 1999 genie.sh
drwxr-xr-x 2 kumar metal 512 may 9 10:31 helpdir
drwxr-xr-x 2 kumar metal 512 may 9 09:57 progs
Directories are easily identified in the listing by the first character of the first column, which
here shows a d. The significance of the attributes of a directory differs a good deal from an ordinary
file. To see the attributes of a directory rather than the files contained in it, use ls –ld with the directory
name. Note that simply using ls –d will not list all subdirectories in the current directory. Strange
though it may seem, ls has no option to list only directories.
File Ownership
When you create a file, you become its owner. Every owner is attached to a group owner.
Several users may belong to a single group, but the privileges of the group are set by the owner of the
file and not by the group members. When the system administrator creates a user account, he has to
assign these parameters to the user:
The user-id (UID) – both its name and numeric representation
The group-id (GID) – both its name and numeric representation
File Permissions
UNIX follows a three-tiered file protection system that determines a file’s access rights. It is
displayed in the following format:
y
Filetype owner (rwx) groupowner (rwx) others (rwx)
For Example:
16
-rwxr-xr-- 1 kumar metal 20500 may 10 19:21 chap02
The first group has all three permissions. The file is readable, writable and executable by the
owner of the file. The second group has a hyphen in the middle slot, which indicates the absence of
write permission by the group owner of the file. The third group has the write and execute bits absent.
This set of permissions is applicable to others.
You can set different permissions for the three categories of users – owner, group and others.
It’s important that you understand them because a little learning here can be a dangerous thing. Faulty
file permission is a sure recipe for disaster
A file or a directory is created with a default set of permissions, which can be determined by
umask. Let us assume that the file permission for the created file is -rw-r--r--. Using chmod command,
we can change the file permissions and allow the owner to execute his file. The command can be used
in two ways:
Relative Permissions
chmod only changes the permissions specified in the command line and leaves the other
permissions unchanged. Its syntax is:
The command assigns (+) execute (x) permission to the user (u), other permissions remain unchanged.
Let initially,
Then, it becomes
Absolute Permissions
Here, we need not to know the current file permissions. We can set all nine permissions
explicitly. A string of three octal digits is used as an expression. The permission can be represented by
one octal digit for each category. For each category, we add octal digits. If we represent the
permissions of each category by one octal digit, this is how the permission can be represented:
We have three categories and three permissions for each category, so three octal digits can
describe a file’s permissions completely. The most significant digit represents user and the least one
represents others. chmod can use this three-digit string as the expression.
18
will assign all permissions to the owner, read and write permissions for the group and only execute
permission to the others.
777 signify all permissions for all categories, but still we can prevent a file from being deleted.
000 signifies absence of all permissions for all categories, but still we can delete a file. It is the
directory permissions that determine whether a file can be deleted or not. Only owner can change the
file permissions. User can not change other user’s file’s permissions. But the system administrator can
do anything.
----------
This is simply useless but still the user can delete this file
On the other hand,
-rwxrwxrwx
The UNIX system by default, never allows this situation as you can never have a secure system.
Hence, directory permissions also play a very vital role here
Directory Permissions
It is possible that a file cannot be accessed even though it has read permission, and can be
removed even when it is write protected. The default permissions of a directory are,
rwxr-xr-x (755)
Example:
mkdir c_progs
ls –ld c_progs
If a directory has write permission for group and others also, be assured that every user can
remove every file in the directory. As a rule, you must not make directories universally writable unless
you have definite reasons to do so.
Usually, on BSD and AT&T systems, there are two commands meant to change the ownership of a
file or directory. Let kumar be the owner and metal be the group owner. If sharma copies a file of
kumar, then sharma will become its owner and he can manipulate the attributes
chown
ls -l note
chgrp
This command changes the file’s group owner. No superuser permission is required.
ls –l dept.lst
In this chapter we considered two important file attributes – permissions and ownership. After
we complete the first round of discussions related to files, we will take up the other file attributes.
MORE FILE ATTRIBUTES
Apart from permissions and ownership, a UNIX file has several other attributes, and in this
chapter, we look at most of the remaining ones. A file also has properties related to its time stamps and
links. It is important to know how these attributes are interpreted when applied to a directory or a
device.
This chapter also introduces the concepts of file system. It also looks at the inode, the lookup
table that contained almost all file attributes. Though a detailed treatment of the file systems is taken
up later, knowledge of its basics is essential to our understanding of the significance of some of the file
attributes. Basic file attributes has helped us to know about - ls –l to display file attributes (properties),
listing of a specific directory, ownership and group ownership and different file permissions. ls –l
provides attributes like – permissions, links, owner, group owner, size, date and the file name.
The hard disk is split into distinct partitions, with a separate file system in each partition. Every
file system has a directory structure headed by root.
All attributes of a file except its name and contents are available in a table – inode (index
node), accessed by the inode number. The inode contains the following attributes of a file:
• File type
• File permissions
• Number of links
• The UID of the owner
• The GID of the group owner
21
• File size in bytes
• Date and time of last modification
• Date and time of last access
• Date and time of last change of the inode
• An array of pointers that keep track of all disk blocks used by the file
Please note that, neither the name of the file nor the inode number is stored in the inode. To know
inode number of a file:
ls -il tulec05
Where, 9059 is the inode number and no other file can have the same inode number in the same file
system.
Hard Links
The link count is displayed in the second column of the listing. This count is normally 1, but the
following files have two links,
All attributes seem to be identical, but the files could still be copies. It’s the link count that seems to
suggest that the files are linked to each other. But this can only be confirmed by using the –i option to
ls.
A file is linked with the ln command which takes two filenames as arguments (cp command).
The command can create both a hard link and a soft link and has syntax similar to the one used by cp.
The following command links emp.lst with employee:
ln emp.lst employee
The –i option to ls shows that they have the same inode number, meaning that they are actually
one end the same file:
You can link multiple files, but then the destination filename must be a directory. A file is considered
to be completely removed from the file system when its link count drops to zero. ln returns an error
when the destination file exists. Use the –f option to force the removal of the existing link before
creation of the new one
Where to use Hard Links
It creates link in directory input_files. With this link available, your existing programs will
continue to find foo.txt in the input_files directory. It is more convenient to do this that modifies all
programs to point to the new path. Links provide some protection against accidental deletion,
especially when they exist in different directories. Because of links, we don’t need to maintain two
programs as two separate disk files if there is very little difference between them. A file’s name is
available to a C program and to a shell script. A single file with two links can have its program logic
make it behave in two different ways depending on the name by which it is called.
We can’t have two linked filenames in two file systems and we can’t link a directory even
within the same file system. This can be solved by using symbolic links (soft links).
Symbolic Links
Unlike the hard linked, a symbolic link doesn’t have the file’s contents, but simply provides the
pathname of the file that actually has the contents.
ln -s note note.sym
Where, l indicate symbolic link file category. -> indicates note.sym contains the pathname for the
filename note. Size of symbolic link is only 4 bytes; it is the length of the pathname of note.
It’s important that this time we indeed have two files, and they are not identical. Removing
note.sym won’t affect us much because we can easily recreate the link. But if we remove note, we
would lose the file containing the data. In that case, note.sym would point to a nonexistent file and
become a dangling symbolic link.
23
Symbolic links can also be used with relative pathnames. Unlike hard links, they can also span
multiple file systems and also link directories. If you have to link all filenames in a directory to another
directory, it makes sense to simply link the directories. Like other files, a symbolic link has a separate
directory entry with its own inode number. This means that rm can remove a symbolic link even if its
points to a directory.
A symbolic link has an inode number separate from the file that it points to. In most cases, the
pathname is stored in the symbolic link and occupies space on disk. However, Linux uses a fast
symbolic link which stores the pathname in the inode itself provided it doesn’t exceed 60 characters.
The Directory
A directory has its own permissions, owners and links. The significance of the file attributes
change a great deal when applied to a directory. For example, the size of a directory is in no way
related to the size of files that exists in the directory, but rather to the number of files housed by it. The
higher the number of files, the larger the directory size. Permission acquires a different meaning when
the term is applied to a directory.
ls -l -d progs
The default permissions are different from those of ordinary files. The user has all permissions,
and group and others have read and execute permissions only. The permissions of a directory also
impact the security of its files. To understand how that can happen, we must know what permissions
for a directory really mean.
Read permission
Read permission for a directory means that the list of filenames stored in that directory is
accessible. Since ls reads the directory to display filenames, if a directory’s read permission is
removed, ls wont work. Consider removing the read permission first from the directory progs,
ls -ld progs
Write permission
We can’t write to a directory file. Only the kernel can do that. If that were possible, any user
could destroy the integrity of the file system. Write permission for a directory implies that you are
permitted to create or remove files in it. To try that out, restore the read permission and remove the
write permission from the directory before you try to copy a file to it.
• The write permission for a directory determines whether we can create or remove files in it
because these actions modify the directory
• Whether we can modify a file depends on whether the file itself has write permission. Changing
a file doesn't modify its directory entry
Execute permission
If a single directory in the pathname doesn’t have execute permission, then it can’t be searched
for the name of the next directory. That’s why the execute privilege of a directory is often referred to
as the search permission. A directory has to be searched for the next directory, so the cd command
won’t work if the search permission for the directory is turned off.
cd progs
When we create files and directories, the permissions assigned to them depend on the system’s
default setting. The UNIX system has the following default permissions for all files and directories.
The default is transformed by subtracting the user mask from it to remove one or more
permissions. We can evaluate the current value of the mask by using umask without arguments,
$ umask
022
This becomes 644 (666-022) for ordinary files and 755 (777-022) for directories umask 000. This
indicates, we are not subtracting anything and the default permissions will remain unchanged. Note
that, changing system wide default permission settings is possible using chmod but not by umask
MODIFICATION AND ACCESS TIMES
A UNIX file has three time stamps associated with it. Among them, two are:
• Time of last file modification ls -l
• Time of last access ls –lu
25
The access time is displayed when ls -l is combined with the -u option. Knowledge of file‘s
modification and access times is extremely important for the system administrator. Many of the tools
used by them look at these time stamps to decide whether a particular file will participate in a backup
or not.
Then, both times are set to the current time and creates the file, if it doesn’t exist.
touch command (without options but with expression) can be used. The expression consists of
MMDDhhmm (month, day, hour and minute).
ls -lu emp.lst
It is possible to change the two times individually. The –m and –a options change the modification and
access times, respectively:
It recursively examines a directory tree to look for files matching some criteria, and then takes
some action on the selected files. It has a difficult command line, and if you have ever wondered why
UNIX is hated by many, then you should look up the cryptic find documentation. How ever, find is
easily tamed if you break up its arguments into three components:
26
The path_list comprises one or more subdirectories separated by white space. There can also be a host
of selection_criteria that you use to match a file, and multiple actions to dispose of the file. This makes
the command difficult to use initially, but it is a program that every user must master since it lets him
make file selection under practically any condition.
The vi Editor
To write and edit some programs and scripts, we require editors. UNIX provides vi editor for BSD
system – created by Bill Joy. Bram Moolenaar improved vi editor and called it as vim (vi improved) on
Linux OS.
vi Basics
vi <filename>
In all probability, the file doesn’t exist, and vi presents you a full screen with the filename
shown at the bottom with the qualifier. The cursor is positioned at the top and all remaining lines of the
screen show a ~. They are non-existent lines. The last line is reserved for commands that you can enter
to act on text. This line is also used by the system to display messages. This is the command mode.
This is the mode where you can pass commands to act on text, using most of the keys of the keyboard.
This is the default mode of the editor where every key pressed is interpreted as a command to run on
text. You will have to be in this mode to copy and delete text
For, text editing, vi uses 24 out of 25 lines that are normally available in the terminal. To enter
text, you must switch to the input mode. First press the key i, and you are in this mode ready to input
text. Subsequent key depressions will then show up on the screen as text input.
After text entry is complete, the cursor is positioned on the last character of the last line. This is
known as current line and the character where the cursor is stationed is the current cursor position. This
mode is used to handle files and perform substitution. After the command is run, you are back to the
default command mode. If a word has been misspelled, use ctrl-w to erase the entire word.
Now press esc key to revert to command mode. Press it again and you will hear a beep. A beep
in vi indicates that a key has been pressed unnecessarily. Actually, the text entered has not been saved
on disk but exists in some temporary storage called a buffer. To save the entered text, you must switch
to the execute mode (the last line mode). Invoke the execute mode from the command mode by
entering a: which shows up in the last line.
ctrl-l
:set showmode
Messages like INSERT MODE, REPLACE MODE, CHANGE MODE, etc will appear in the last line.
Pressing ‘i’ changes the mode from command to input mode. To append text to the right of the cursor
position, we use a, text. I and A behave same as i and a, but at line extremes
I inserts text at the beginning of line. A appends text at end of line. o opens a new line below the
current line
COMMAND FUNCTION
i inserts text
a appends text
I inserts at beginning of line
A appends text at end of line
o opens line below
O opens line above
r replaces a single character
s replaces with a text
S replaces entire line
When you edit a file using vi, the original file is not distributed as such, but only a copy of it
that is placed in a buffer. From time to time, you should save your work by writing the buffer contents
to disk to keep the disk file current. When we talk of saving a file, we actually mean saving this buffer.
You may also need to quit vi after or without saving the buffer. Some of the save and exit commands
of the ex mode is:
28
Command Action
:W saves file and remains in editing mode
:x saves and quits editing mode
:wq saves and quits editing mode
:w <filename> save as
:w! <filename> save as, but overwrites existing file
:q quits editing mode
:q! quits editing mode by rejecting changes made
:sh escapes to UNIX shell
:recover recovers file from a crash
Navigation
A command mode command doesn’t show up on screen but simply performs a function.
To move the cursor in four directions,
k moves cursor up
j moves cursor down
h moves cursor left
l moves cursor right
Word Navigation
Moving by one character is not always enough. You will often need to move faster along a line. vi
understands a word as a navigation unit which can be defined in two ways, depending on the key
pressed. If your cursor is a number of words away from your desired position, you can use the word-
navigation commands to go there directly. There are three basic commands:
Example,
0 or |
Faster movement can be achieved by scrolling text in the window using the control keys. The
two commands for scrolling a page at a time are
Absolute Movement
The editor displays the total number of lines in the last line
Editing Text
The editing facilitates in vi are very elaborate and invoke the use of operators. They use operators,
such as,
d delete
y yank (copy)
Deleting Text
Moving Text
Copying Text
Joining Lines
vim (LINUX) lets you undo and redo multiple editing instructions. u behaves differently here;
repeated use of this key progressively undoes your previous actions. You could even have the original
file in front of you. Further 10u reverses your last 10 editing actions. The function of U remains the
same.
You may overshoot the desired mark when you keep u pressed, in which case use ctrl-r to redo
your undone actions. Further, undoing with 10u can be completely reversed with 10ctrl-r. The undoing
limit is set by the execute mode command: set undolevels=n, where n is set to 1000 by default.
The . (dot) command is used for repeating the last instruction in both editing and command mode
commands
For example:
2dd deletes 2 lines from current line and to repeat this operation, type. (dot)
/ search forward
? search backward
/printf
The search begins forward to position the cursor on the first instance of the word
?pattern
Searches backward for the most previous instance of the pattern
Command Function
We can perform search and replace in execute mode using :s. Its syntax is,
:address/source_pattern/target_pattern/flags
Interactive substitution: sometimes you may like to selectively replace a string. In that case, add the c
parameter as the flag at the end:
:1,$s/director/member/gc
Each line is selected in turn, followed by a sequence of carets in the next line, just below the pattern
that requires substitution. The cursor is positioned at the end of this caret sequence, waiting for your
response.
The ex mode is also used for substitution. Both search and replace operations also use regular
expressions for matching multiple patterns.
vi Editor Information
To enter vi:
To enter vi from the command line, use any of the forms below:
vi file Invoke vi editor on file
vi file1
Invoke vi editor on files sequentially
file2
view file Invoke vi editor on file in read only mode
vi +n file Invoke vi editor; editing starts on line n
vi -r file Recover changes made to file after a system
crash
32
ex Commands
To enter an ex command from vi:
address is the line number or range of lines that are the object of command. If no address is given, the
current line is the object of the command.
Address Symbols
In ex command syntax, address can be specified by any of the following:
Option Symbols
In ex command syntax, options may be any of the following:
Commands
append [address] a[!]
text
.
Append text at specified address, or at present address if none is specified. Add a ! to
switch the autoindent setting that will be used during input. That is, if autoindent was
enabled, ! disables it.
copy [address] co destination
Copy the lines included in address to the specified destination address. The command t is a
synonym for copy.
delete [address] d [buffer]
Delete the lines included in address. If buffer is specified, save or append the text to the
named buffer.
edit e[!] [+n] [filename]
Begin editing on filename. If no filename is given, bring in another copy of the curent file.
Add a ! to edit the new file even if the current file has not been saved since the last change.
With the +n argument, begin editing on line n.
insert [address] i[!]
text
.
Insert text at line before the specified address, or at present address if none is specified.
Add a ! to switch the autoindent setting during input of text.
map map char commands
Define a macro named char in visual mode with the specified sequence of commands.
char is usually a single character, or the sequence #n, representing a function key on the
keyboard.
mark [address] ma char
Mark the specified line with char, a single lowercase letter. Return later to the line with 'x.
move [address] m destination
Move the lines specified by address to the destination address.
next n[!] [[+command]filelist]
Edit the next file from the command-line argument list. Use args to list these files. If
filelist is provided, replace the current argument list with filelist and begin editing on the
first file; if command is given (containing no spaces), execute command after editing the
first such file.
put [address] pu [char]
Restore previously deleted or yanked lines, from named buffer specified by char, to the
line specified by address; if char is not specified, the last deleted or yanked text is restored.
quit quit[!]
Terminate current editing session. Use ! to discard changes made since the lsat save. If the
editing session includes additional files in the argument list that have not yet been
34
vi Commands
vi has two "modes", command and insert. Insert mode (text entry) is terminated by <escape>, which
toggles back to command mode. <escape> in command mode is ignored.
c Begin a change.
d Begin a deletion.
y Begin a yank (or copy).
If the current line is the object of the operation, then the operator is the same as the object: cc, dd, yy.
Otherwise, the editing operators act on objects specified by cursor-movement commands or pattern-
matching commands. n and m are the number of times the operation is performed, or the number of
objects the operation is performed on. If both n and m are specified, the effect is n x m.
word Includes characters up to a space or punctuation mark. A capitalized object is a variant form
that recognizes only blank spaces.
sentence Is up to ., !, ? followed by two spaces.
paragrap
Is up to next blank line or paragraph macro defined by para=option.
h
section Is up to next section heading defined by sect=option.
Examples
Movement Commands
Character:
h,j,k,l Left, down, up, right (direction arrows)
Text:
w, W, b, B Forward, backward by word
e, E End of word
), ( Beginning of next, previous sentence
},{ Beginning of next, previous paragraph
]],[[ Beginning of next, previous section
36
Lines:
0, $ First, last position of current line
^ First character of current line (ignore spaces)
+, - First character of next, previous line
n| Column n of current line
H Top line of screen
M Middle line of screen
L Last line of screen
nH n (number) of lines after top line
nL n (number) of lines before last line
Screens:
Ctrl-F Scroll forward one screen
Ctrl-B Scroll backward one screen
Ctrl-D, Ctrl-U Scroll down, up one-half screen
Ctrl-E, Ctrl-Y Show one more line at bottom, top of window
z<Return> Reposition line with cursor: to top of screen
z. Reposition line with cursor: to middle of screen
z- Reposition line with cursor: to bottom of screen
Ctrl-L, Ctrl-R Redraw screen (without scrolling)
Searches:
/pattern Search forward for pattern
?pattern Search backward for pattern
n, N Repeat last search in same, opposite direction
/, ? Repeat previous search forward, backward
Fx Search forward for character x in current line
Fx Search backward for character x in current line
Tx Search forward for character before x in current line
Tx Search backward for character after x in current line
; Repeat previous current-line search
, Repeat previous current-line search in opposite direction
Line number:
Ctrl-G Display current line number and file name
nG Move to line number n
37
G Move to last line in file
:n Move to line number n
Marking
position:
Mx Mark current position as x
`x Move cursor to x (grave character)
`` Return to previous mark or context (two grave characters)
'x Move to beginning of line containing mark x (single quote)
'' Return to beginning of line containing previous mark (two single quotes)
Editing Commands
Insert:
i, a Insert text before, after cursor
I, A Insert text at beginning, end of line
o, O Open new line for text below, above cursor
Change:
R Change character (no <escape> required)
Cw Change word
Cc Change currnt line
C Change to end of line
R Type of characters
S Delete character and substitute text
S Delete current line and substitute text
Delete, move:
X Delete character
X Delete character before cursor
Dw Delete word
Dd Delete current line
D Delete to end of line
p, P Put deleted text after, before cursor
"np Put text from delete buffer n after cursor (for last nine
deletions)
Yank:
38
Yw Yank (copy) word
Yy Yank current line
"ayy Yank current line into named buffer a
p, P Put yanked text after, before cursor
"aP Put text from buffer a before cursor
Other
commands:
. Repeat last edit command
u, U Undo last edit; restore current line
J Join two lines
Exit Commands
ZZ Write (save) and quit file
:x Write (save) and quit file
:wq Write (save) and quit file
:w Write (save) file
:w! Write (save) file (overriding protection)
:30, 60w
Write from line 30 through 60 as newfile
newfile
:30, 60w >> file Write from line 30 through line 60 and append to file
:w %.new Write current buffer named file as file.new
:q Quit file
:q! Quit file (overriding protection)
Q Quit vi and invoke ex
:e file2 Edit file2 without leaving vi
:n Edit next file
:e! Return to version of current file at time of last write (save)
:e# Edit alternate file
% Current filename
# Alternate filename