0% found this document useful (0 votes)
154 views

Unix and Shell Programming: 1. Overview of Operating System

The document provides an overview of the Unix operating system and shell programming. It discusses [1] the architecture and history of Unix, [2] common Unix commands like vi editor, processes, communication tools, and filters, [3] shell programming basics including shell scripts, variables, conditionals, and loops, and [4] an introduction to Perl programming. The document serves as a guide to learning Unix and shell scripting, covering fundamental concepts, commands, and programming techniques.

Uploaded by

Bhawya Gupta
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
154 views

Unix and Shell Programming: 1. Overview of Operating System

The document provides an overview of the Unix operating system and shell programming. It discusses [1] the architecture and history of Unix, [2] common Unix commands like vi editor, processes, communication tools, and filters, [3] shell programming basics including shell scripts, variables, conditionals, and loops, and [4] an introduction to Perl programming. The document serves as a guide to learning Unix and shell scripting, covering fundamental concepts, commands, and programming techniques.

Uploaded by

Bhawya Gupta
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 38

1

Unix and Shell Programming

1. Overview of Operating System


Introduction, OS and its services, Character vs GUI, Types of OS , Unix
family, Brief History of the Unix Operating System –Introduction, Features of
Unix, Historical development, variations in Unix systems, Unix Architecture.
2. Understanding the Unix command
Locating commands, Internal and External commands, Command Structure,
Flexibility of command usuage, man,knowing your machine.
General Purpose Utilities- Cal, date, echo, printf, bc, script, passwd, who,
uname, tty, sty.
The File System: File, parent-child relationship, the HOME variable, pwd, cd,
mkdir, rmdir, absolute pathnames, relative pathnames, ls, the Unix file
system.
Handling ordinary files – cat, cp, rm, mv, more, lp, wc, od, cmp, diff,
dos2unix and unix2dos, compressing and archiving files, gzip and gunzip,
tar, zip and unzip, ls-l, chmod, File Systems and Inodes, Hardlinks, Symbolic
links, umask, find.
3. The vi editor
vi basics, input mode, saving text and quitting, navigation, editing text,
undoing last editing instructions,repeating the last command, searching for
a pattern, substitution.
Advanced vi – operators, the ex Mode, storing multiple text sections,
undoing multiple line deletions, entering control characters, searching for a
character, customizing vi.
4. The Process – Basics, ps, system processes,process creation, Internal and
external commands, running jobs in background, nice, killing process with
signals, job control, at and batch, cron, time, Environment variables,
aliases, command history.
Communication and Email – finger, talk, mesg, email basics, mailx,
pine,ifconfig, ping,netstat, ftp,telnet.
Simple filters – pr, head, tail, cut, paste, sort, uniq, tr, grep, ERE and egrep,
sed.
Awk –awk filtering, splitting line into fields, printf, the comparison operator,
number processing, variables, storing awk programs in a file,The BEGIN and
END Sections, Built in variables, arrays, functions, control flow, looping with
for, looping with while.

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

1. (a) Explain the architecture of UNIX operating system.


08
Ans: In UNIX the division of labour is between two agencies-the kernal and the shell.the kernal
interacts with the machine’s hardware, the shell with the user.

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.

1. (b) Explain POSIX 02

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.

2. (a) Explain the salient features of the unix operating system


08
Ans: the features of the UNIX operating system are:

1. The File and Process


A file to UNIX is just an array of bytes and can contain virtually anything-text, object code or a
directory structure.unix provides a vast array of text manipulation tools that can edit these files
without using an editor.

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.

2. UNIX:a multiuser system


in unix, the resources are actually shared between all users.the computer breaks up a unit of
time into several segments, and each user is allotted a segment.so at any point in time, the
machine will be doing the job of a single user.the moment the allocated time expires, the
previous job is kept in abeyance and the next user’s job is taken up.this process goes on till the
circle has turned full-circle and the first user’s job is taken up once again.

3. UNIX: a multitasking system


A single user can also run multiple tasks concurrently; the kernal is designed to handle a user’s
multiple needs.

4. The building- block approach


Many UNIX tools are designed with the requirement that the output of one tool be used as
input to another.

5. The UNIX Toolkit


Unix represents the kernal, but the kernal by itself can’t do anything that can benefit the
user.To properly exploit the power of unix, we need to use the host of applications that are
shipped with every unix system.There are general-purpose tools,text manipulation
utilities(called filters),compilers and interpreters,networked applications and system
administration tools.
5

6. Pattern matching

The *(known as a metacharacter) is a special character used by the system to indicate


that it can match a number of filenames.unix features elaborate pattern matching schemes that
use several characters from this matacharacter set.

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.

2. (b) Explain tput, exit commands 02

Ans: tput clear: clearing the screen

tput command to clear the screen


tput clear

The execution of this vanishes whatever was typed and the prompt and cursor are positioned at
the top-left corner of the screen.

Exit: this command suspends the session

$ exit

login:

The login: message confirms that the session has been terminated, thus making it available for
the next user.

3. (a) explain internal and external commands with example


04
6

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.

3. (b) Explain the man documentation 06

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.

4. Explain cal, echo, printf, bc, tty commands with example


10

Ans: cal: THE CALENDER


The cal command is used to see the calender of any specific month or a complete year.the facility is
totally accurate and takes into account the leap year adjustments that took place in the year
$ Cal
It displays the calender of the current month.
The syntax also tells us that when cal is used with arguments, the month is optional but the year is
not.To see the calender for the month of March 2003, you need two arguments:

$ 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

Echo: displaying a message

Echo is used in two ways

 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).

$ echo “Enter filename:\c”


Enter filename: $ _
This is how echo is used in a shell script to accept input from the terminal.

Escape sequence used by echo


\a bell
\b backspace
\c no newline (cursor in same line)
\f formfeed
\n newline
\r carriage return
\t tab
\v vertical tab
\\ Backslash
\0n ASCII character represented by the octal value n, where can’t exceed 0377(decimal value
255)

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]
$ _

12*12; 2^32 ; multiple calculation in the same line


144
4294967296

To enable floating-point computation, the sacle have to be set to the number of digits of precision

Scale=2
17/7
2.42

bc is quite useful in converting numbers from one base to another

ibase=2
11001010
202 ;output in decimal-base 10

The reverse is also possible

obase=2
14
1110

bc also handles hexadecimal numbers


obase=16
14
E

tty: KNOWING YOUR TERMINAL

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

We can print only month, using the format +%m:

$ date +%m
12

Or the month name:

$ date +%h
Dec

or you can combine them in one command:

$ date +”%h %m”


Dec 12

Other format specifiers are

d-the day of the month


y-the last two digit of the year
H, M and S-the hour, minute and second, respectively
D-the date in the format mm/dd/yy
T-the time in the format hh:mm:ss

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

stty: this command displays and changes settings


The –a option displays the current settings.the setting signifies [Ctrl-d] interrupts a program, [Ctrl-h]
erase a character and [Ctrl-u] kills a character.

Who:WHO ARE THE USERS?


UNIX maintains an account of all user who are logged on to the system.the who command displays an
informative listing of these users

$ who

root console Aug 1 07:51 (:0)


kumar pts/10 Aug 1 07:56 (pc123.heavens.com)
sharma pts/6 Aug 1 02:10 (pc125.heavens.com)

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: RECORDING YOUR SESSION


This command lets you record your login session in a file.

$ 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

Appends to it or uses a different log file.

6. (a) explain the different types of files supported in UNIX


06

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.

6. (b) explain the UNIX file system tree 04

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

Ans: pwd: pwd command tells you your current directory

$ 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

cp:overwrite until (yes/no) ? y


A y at this prompt overwrites the file.

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:

rm chap01 chap02 chap03

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: the more command displays its output a page at a time.

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

8. (a) explain the use of ls command with –x,-F,-a & -r options


04

Ans: ls command is used to list the names of the files available in the directory

ls with –x option is used to display filenames in multiple column

$ ls -x

08_packets.html TOC.sh calender cptodos.sh


dept.lst emp.lst helpdir progs

ls with –F option is used to identify directories and executable files.

ls with –a option lists all hidden files all with the other files.

ls with –r option sorts filenames in reverse order.

8. (b) explain absolute pathname, relative pathname, argument and option?


04

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

-l is an argument to ls by defination but it’s a special argument known as an option.

8. (c) Explain file command and home variable? 02

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.

Basic File Attributes

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 –l to display file attributes (properties)


• Listing of a specific directory
• Ownership and group ownership
• Different file permissions

Listing File Attributes

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:

• File type and Permissions


• Links
• Ownership
• Group ownership
• File size
• Last Modification date and time
• File name

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

Listing Directory Attributes

ls -d will not list all subdirectories in the current directory


For example,

ls –ld helpdir progs


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

rwx r-x r--

owner/user group owner others

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

Changing File Permissions

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:

In a relative manner by specifying the changes to the current permissions


In an absolute manner by specifying the final permissions

Relative Permissions

chmod only changes the permissions specified in the command line and leaves the other
permissions unchanged. Its syntax is:

chmod category operation permission filename(s)

chmod takes an expression as its argument which contains:


user category (user, group, others)
operation to be performed (assign or remove a permission)
type of permission (read, write, execute)

Category operation permission


u - user + assign r - read
g - group - remove w - write
o - others = absolute x - execute
a - all (ugo)

Let us discuss some examples:


Initially,
-rw-r--r-- 1 kumar metal 1906 sep 23:38 xstart

chmod u+x xstart


17
-rwxr--r-- 1 kumar metal 1906 sep 23:38 xstart

The command assigns (+) execute (x) permission to the user (u), other permissions remain unchanged.

chmod ugo+x xstart or


chmod a+x xstart or
chmod +x xstart

-rwxr-xr-x 1 kumar metal 1906 sep 23:38 xstart

chmod accepts multiple file names in command line

chmod u+x note note1 note3

Let initially,

-rwxr-xr-x 1 kumar metal 1906 sep 23:38 xstart

chmod go-r xstart

Then, it becomes

-rwx--x--x 1 kumar metal 1906 sep 23:38 xstart

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:

• Read permission – 4 (octal 100)


• Write permission – 2 (octal 010)
• Execute permission – 1 (octal 001)

Octal Permissions Significance


0 --- no permissions
1 --x execute only
2 -w- write only
3 -wx write and execute
4 r-- read only
5 r-x read and execute
6 rw- read and write
7 rwx read, write and execute

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

Using relative permission, we have,

chmod a+rw xstart

Using absolute permission, we have,

chmod 666 xstart

chmod 644 xstart

chmod 761 xstart

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.

The Security Implications

Let the default permission for the file xstart is


-rw-r--r--
chmod u-rw, go-r xstart or

chmod 000 xstart

----------

This is simply useless but still the user can delete this file
On the other hand,

chmod a+rwx xstart

chmod 777 xstart

-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

We can use chmod Recursively.

chmod -R a+x shell_scripts


19
This makes all the files and subdirectories found in the shell_scripts directory, executable by all users.
When you know the shell meta characters well, you will appreciate that the * doesn’t match filenames
beginning with a dot. The dot is generally a safer but note that both commands change the permissions
of directories also.

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)

A directory must never be writable by group and others

Example:

mkdir c_progs

ls –ld c_progs

drwxr-xr-x 2 kumar metal 512 may 9 09:57 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.

Changing File Ownership

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 changing file owner and chgrp changing group owner

On BSD, only system administrator can use chown


On other systems, only the owner can change both

chown

Changing ownership requires superuser permission, so use su command

ls -l note

-rwxr----x 1 kumar metal 347 may 10 20:30 note

chown sharma note; ls -l note

-rwxr----x 1 sharma metal 347 may 10 20:30 note


20
Once ownership of the file has been given away to sharma, the user file permissions that
previously applied to Kumar now apply to sharma. Thus, Kumar can no longer edit note since there is
no write privilege for group and others. He can not get back the ownership either. But he can copy the
file to his own directory, in which case he becomes the owner of the copy.

chgrp

This command changes the file’s group owner. No superuser permission is required.

ls –l dept.lst

-rw-r--r-- 1 kumar metal 139 jun 8 16:43 dept.lst

chgrp dba dept.lst; ls –l dept.lst

-rw-r--r-- 1 kumar dba 139 jun 8 16:43 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.

File Systems and inodes

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.

n partitions = n file systems = n separate root directories

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

9059 -rw-r--r-- 1 kumar metal 51813 Jan 31 11:15 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,

-rwxr-xr-- 2 kumar metal 163 Jull 13 21:36 backup.sh


-rwxr-xr-- 2 kumar metal 163 Jul 13 21:36 restore.sh

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.

ls -li backup.sh restore.sh

478274 -rwxr-xr-- 2 kumar metal163 jul 13 21:36 backup.sh


478274 -rwxr-xr-- 2 kumar metal163 jul 13 21:36 restore.sh

ln: Creating Hard Links

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:

ls -li emp.lst employee

29518 -rwxr-xr-x 2 kumar metal 915 may 4 09:58 emp.lst


29518 -rwxr-xr-x 2 kumar metal 915 may 4 09:58 employee
22
The link count, which is normally one for unlinked files, is shown to be two. You can increase
the number of links by adding the third file name emp.dat as:

ln employee emp.dat ; ls -l emp*

29518 -rwxr-xr-x 3 kumar metal 915 may 4 09:58 emp.dat


29518 -rwxr-xr-x 3 kumar metal 915 may 4 09:58 emp.lst
29518 -rwxr-xr-x 3 kumar metal 915 may 4 09:58 employee

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

ln data/ foo.txt input_files

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

ls -li note note.sym

9948 -rw-r--r-- 1 kumar group 80 feb 16 14:52 note


9952 lrwxrwxrwx 1 kumar group 4 feb16 15:07note.sym ->note

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

drwxr-xr-x 2 kumar metal 320 may 9 09:57 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

drwxr-xr-x 2 kumar metal 128 jun 18 22:41 progs

chmod -r progs ; ls progs

progs: permission denied

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.

chmod 555 progs ; ls –ld progs


24

dr-xr-xr-x 2 kumar metal 128 jun 18 22:41 progs


cp emp.lst progs

cp: cannot create progs/emp.lst: permission denied

• 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.

chmod 666 progs ; ls –ld progs

drw-rw-rw- 2 kumar metal 128 jun 18 22:41 progs

cd progs

permission denied to search and execute it

umask: DEFAULT FILE AND DIRECTORY PERMISSIONS

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.

rw-rw-rw- (octal 666) for regular files

rwxrwxrwx (octal 777) for 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.

TOUCH COMMAND – changing the time stamps

To set the modification and access times to predefined values, we have,

touch options expression filename(s)

touch emp.lst (without options and expression)

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).

touch 03161430 emp.lst ; ls -l emp.lst

-rw-r--r-- 1 kumar metal 870 mar 16 14:30 emp.lst

ls -lu emp.lst

-rw-r--r-- 1 kumar metal 870 mar 16 14:30 emp.lst

It is possible to change the two times individually. The –m and –a options change the modification and
access times, respectively:

touch command (with options and expression)

-m for changing modification time


-a for changing access time

touch -m 02281030 emp.lst ; ls -l emp.lst

-rw-r--r-- 1 kumar metal 870 feb 28 10:30 emp.lst

touch -a 01261650 emp.lst ; ls -lu emp.lst

-rw-r--r-- 1 kumar metal 870 jan 26 16:50 emp.lst

find : locating files

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

find path_list selecton_criteria action


where,
• Recursively examines all files specified in path_list
• It then matches each file for one or more selection-criteria
• It takes some action on those selected files

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

To add some text to a file, we invoke,

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.

The Repeat Factor


27
vi provides repeat factor in command and input mode commands. Command mode command k
moves the cursor one line up. 10k moves cursor 10 lines up.
To undo whenever you make a mistake, press
Esc u

To clear the screen in command mode, press

ctrl-l

Don’t use (caps lock) - vi commands are case-sensitive


Avoid using the PC navigation keys

Input Mode – Entering and Replacing Text

It is possible to display the mode in which is user is in by typing,

: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

• r<letter> replacing a single character


• s<text/word> replacing text with s
• R<text/word> replacing text with R
• Press esc key to switch to command mode after you have keyed in text

Some of the input mode commands are:

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

Saving Text and Quitting – The ex Mode

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:

b moves back to beginning of word


e moves forward to end of word
w moves forward to beginning word

Example,

5b takes the cursor 5 words back


3w takes the cursor 3 words forward

Moving to Line Extremes

Moving to the beginning or end of a line is a common requirement.


To move to the first character of a line

0 or |

30| moves cursor to column 30


$ moves to the end of the current line
The use of these commands along with b, e, and w is allowed
29
Scrolling

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

ctrl-f scrolls forward


ctrl-b scrolls backward

10ctrl-f scroll 10 pages and navigate faster

ctrl-d scrolls half page forward


ctrl-u scrolls half page backward

The repeat factor can also be used here.

Absolute Movement

The editor displays the total number of lines in the last line

Ctrl-g to know the current line number


40G goes to line number 40
1G goes to line number 1
G goes to end of file

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

x deletes a single character


dd delete entire line
yy copy entire line
6dd deletes the current line and five lines below

Moving Text

Moving text (p) puts the text at the new location.


p and P place text on right and left only when you delete parts of lines. But the same keys get
associated with “below” and “above” when you delete complete lines

Copying Text

Copying text (y and p) is achieved as,


30
yy copies current line
10yy copies current line & 9 lines below

Joining Lines

J to join the current line and the line following it


4J joins following 3 lines with current line

Undoing Last Editing Instructions

In command mode, to undo the last change made, we use u


To discard all changes made to the current line, we use U

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.

Repeating the Last Command

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)

Searching for a Pattern

/ 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

Repeating the Last Pattern Search

n repeats search in same direction of original search


n doesn’t necessarily repeat a search in the forward direction. The direction depends on the
search command used. If you used? printf to search in the reverse direction in the first place, then n
also follows the same direction. In that case, N will repeat the search in the forward direction, and not
n.
31
Search and repeat commands

Command Function

/pat searches forward for pattern pat


?pat searches backward for pattern pat
n repeats search in same direction along which previous search was made
N repeats search in direction opposite to that along which previous search was made

Substitution – search and replace

We can perform search and replace in execute mode using :s. Its syntax is,

:address/source_pattern/target_pattern/flags

:1,$s/director/member/g can also use % instead of 1,$


:1,50s/unsigned//g deletes unsigned everywhere in lines 1 to 50
:3,10s/director/member/g substitute lines 3 through 10
:.s/director/member/g only the current line
:$s/director/member/g only the last line

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:

To enter an ex command from vi, use this form:

:[address] command [options]

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:

1,$ All lines in the file.


x,y Lines x through y.
Lines x through y, with current line reset to
x;y
x.
0 Top of file.
. Current line.
n Absolute line number n.
$ Last line.
% All lines; same as 1,$.
x-n n lines before x.
x+n n lines after x.
-[n] One or n lines previous.
+[n] One or n lines ahead.
'x Line marked with x.
'' Previous mark.
/pat / or ?pat
Ahead or back to line matching pat.
?

Option Symbols
In ex command syntax, options may be any of the following:

! Indicates a variant form of the command, overriding the normal behavior.


coun The number of times the command is to be repeated. count cannot precede the command,
t because a number preceding an ex command is treated as a line address. d3 deletes three lines
beginning with the current line; 3d deletes line 3.
file The name of a file that is affected by the command. % stands for current file; # stands for
previous file.
33

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

accessed, quit by typing q! or by typing q twice.


read [address] r filename
Copy the text of filename at the specified address. If filename is not specified, the current
filename is used.
read [address] r !command
Read in the output of command into the text after the line specified by address.
substitute [address] s [/pattern/repl/] [options]
Replace each instance of pattern on the specified lines with repl. If pattern and repl are
omitted, repeat last substitution. An option of g substitutes all instances of pattern on the
line. An option of c prompts for confirmation before change.
undo u
Reverse the changes made by the last editing command.
write [address] w[!] [[>>]filename]
Write lines specified by address to filename, or full contents of buffer if address is not
specified. If filename is also omitted, save the contents of the buffer to the current
filename. if >> filename is used, write contents to the end of the specified filename. Add a
! to force the editor to write over any current contents of filename.
yank [address] ya [char] [count]
Place lines specified by address in named buffer indicated by char, or if no char is
specified place in general buffer.
z [address] z [type] [count]
Print a window of text with line specified by address at the top. type can be one of:
+ Place specified line at the top of the window (default).
- Place specified line at bottom of the window.
. Place specified line in the center of the window.
^ Print the previous window.
= Place specified line in the center of the window and leave the current line at this line.
count specifies the number of lines to be displayed.
! [address] !command
Execute command in a shell. If address is specified, apply the lines contained in address as
standard input to command, and replace the lines with the output.

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.

In vi, commands have the following general form:

[n] operator [m] object


35
The basic editing operators are:

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.

An object can represent any of the following text blocks:

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

2cw Change the next two words.


d} Delete up to next paragraph.
d^ Delete back to beginning of line.
5yy Copy the next five lines.
y]] Copy up to the next section.

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

You might also like