Title: Unix Overview
1Unix Overview
2Expectation from this training
This is not an exhaustive training on Unix ,
covering all the arenas with full details.
Even the topics covered in this presentation are
not all inclusive.
But, it will definitely help you to be a
confident sailor in the ocean of Unix no matter
what the circumstance is.
3Dont be nervous,please
This training will teach you about 90 commands!!!
And will make you bore with more than 350
slides!!!!
But dont be nervous remember the utilities of
the commands for this presentation will be
with you for the rest of your life to provide you
the syntax for using them.
4 Duration 15 Hours ( 3 Days)
Schedule 29th Sept-1st Oct,2003
Timings 1100 am 1 pm 200
pm 5 pm
5Purpose
Get introduced to Unix Operating System
To get acquainted with the basic Unix commands
To learn a bit of Shell Programming
6Operating System
An operating system is a living, breathing
software entity. The soul of the computing
machine, it is the nervous system that turns
electrons and silicon into a personality. It
brings life to the computer - from Mike
Gancarz's "The UNIX Philosophy"
The OS sits between users and hardware providing
translation services. It speaks the language of
the hardware to perform basic tasks such as the
definition of memory or the allocation of disk
space using the hardware.
7Unix Operating System
Shell
Kernel
Hardware
In UNIX, the operating system is broken into
three pieces the kernel, the shell, and the
built-in utilities. The kernel is responsible for
low level hardware communication, the shell
provides human users with a user-friendly
interface, and the built-in utilities provide
basic tools for doing work.
8Kernel
- Heart of The Unix OS.
- Collection of C programs directly communicating
with hardware - Part of Unix system loaded into memory when Unix
is booted
- Manages-
- System resources
- Allocates time between user and processes
- Decides process priorities
Exit
9Shell
- Human interface point for Unix
- Program layer provides an environment for the
user to enter commands to get desired results. - Korn Shell, Bourne Shell, C Shell are various
shells used by Unix users
Exit
10User login process
- Unix booted.
- Program Unix(kernel) is booted into main memory,
and remains active till the computer is shut down - Program init runs as a background task and
remains running till shutdown
11- User attempts to log in.
- Kernel calls program init.
- init scans file /etc/inittab , which lists the
ports with terminals and their characteristics
and returns an active open terminal to init. - init calls program getty, which issues a
login prompt in the monitor - User enters login and password
12- getty calls program login which scans file
/etc/passwd to match username and password - After validation, control passes to session
startup program /bin/sh , session startup program - Program /bin/sh reads file /etc/profile and
.profile and sets up system wide and user
specific environment. - User gets a shell prompt
Exit
13Understanding Commands
Controlling Environment
General Purpose Utilities
Process
System Administration
Handling Files
Filters
Communication
14Understanding Unix Commands
By end of this section , you will be able to know
What a command is?
Which program related to a command
Man get online help of commands
Alias Call a Command by another name
History previously executed commands
15- To get work done by Unix, there is no way but to
execute commands. - Commands can be typed in from keyboard or taken
from a file - Unix offers a variety of commands for each
category of jobs. - Commands execute a program in the background
which performs the desired job
16Independent Commands Do not require any input
for execution pwd
/home/ems2000 Dependent Commands Require
input for execution type ls ls is a tracked
alias for /usr/bin/ls Mixed Commands- Can work
independently/dependently
ls input queue
sentwebcatalogs web
ls queue queue
17General syntax to use commands ltcommandgt
ltoption flaggt ltargumentsgt A statement asking
for execution of a command usually consists of
three distinct sections- ltcommandgt Keyword for
the command ltoption flaggt Starts with - sign.
Decides the nature of output from the results of
command execution ltargumentsgt May be a string
or the name of file(s) on which the command will
act upon for desired output. Example grep -l
ems2000 .sh The above command from the OS
prompt searches for the string ems2000 in all
the files with extension .sh and shows the name
of the files containing it.
18More than one commands can be stated from OS
prompt at a time pwdtty /home/ems2000/queue /dev
/pts/tb First, pwd command is executed which
displays the output /home/ems2000/queue Then ,
tty command shows the terminal no
/dev/pts/tb Any number of commands can be
specified at the OS prompt for execution
separated by a A command can spawn more than
one lines echo Hello Hello
19which
Shows the name of the program related to the
command
Syntax which ltcommandgt
Example which ls /usr/bin/ls
Other similar commands are type ltcommandgt
whence ltcommandgt
20man
Displays the online manual page for a given
command, file, subroutine etc.
Use Significance
man ltcommandgt Shows the manual help page for the command
man f ltcommandgt Provides one line details about the command
man k ltkeywordgt Provides a list of summary info about the manual sections in the keyword database for specified keyword ltkeywordgt
21Examples
man which
22alias
Short hand notation of one/more than one commands
Syntax alias ltalias_namegtltvaluegt
Example- alias sdfls lswc l sdf input
queue sentwebcatalogs logfile
s sap web pricelist_feed
scripts webcatalogs 9 To unalias
unalias ltalias_namegt
23history
- Korn shell command.
- Shows an automatic recording of the commands
entered, kept as a numbered list in a special
disk file in the home directory and preserve it
from login session to session. - Commands from the history list can be re-executed
using the tracking number.
24- Can be used for-
- Viewing the previously executed commands
- Re-submit a previously executed command from
the list using r command - Modify a previous command in the list and
execute it - Environment variables-
- HISTFILE File name of Korn shell history
file - HISTSIZE Integer number containing the
maximum number of commands to be retained in
history list. Default is 16 for Korn shell
25Use Significance
history Shows last 16 lines of history in Korn shell
history 5 Shows last 5 commands from history list
history 5 Shows from command number 5 onwards in history list
history ls Shows recent ls command and from that line onwards in history list
history 5 Shows from command number 5 onwards in history list
r n Re-execute the command in line number n in history list
r -n Executes the nth last command executed
r vi Re-execute the last vi command
r prog1.shprog2.sh vi If the earlier vi command was vi prog1.sh , then the command to be executed is vi prog2.sh
26(No Transcript)
27General Purpose Utilities
By end of this section , you will be able know
banner set up poster
uptime System info
expr Calculations
cal get Calendar
login server login
factor factor number
date get current date
telnet server login
primes-Prime number
calendar get schedule
exit- exit current shell
units-Unit conversion
who User information
lock lock a terminal
tput-Control display
tty terminal information
script get the whole job
time-Time taken by a command
uname- machine info
bc Unix Calculator
28banner
Creates posters by blowing up its arguments on
the screen. Each line can display a maximum of
ten characters
Syntax banner lttextgt
Use Significance
Banner Hello Jim In a single line, Hello Jim will be shown as a poster
Banner Hello Jim The word Hello will be shown in one line and Jim in the next line as poster
29Example
30cal
Print the calendar for a year / for a particular
month of a year
Syntax cal ltmongt lt4 digit yeargt
Use Significance
cal 2003 Shows calendar for the year 2003
cal 2 1997 Shows the calendar for February 2003
cal dec 1995 Shows calendar for December 1995
cal ja 1998 Shows calendar for January 1998
cal ju 2000 Shows calendar for June 2000
cal f 1999 Shows calendar for February 1999
31date
Shows the current date in different formats/sets
the current date
Syntax date ltflag for formatting optionsgt
Use Significance
date Shows the current date as a combination of - Three letter word for day of the week/ Short abbreviation for the current month/Day of the month Time in hhmmss/Time zone/4 digit year date Wed Sep 10 020633 MDT 2003
date mmddhhmmyy Sets the Unix system clock to the date and time specified
date a Abbreviated weekday name ( eg., Wed)
32Use Significance
date A Full weekday name(eg., Wednesday)
date b Full month name(Jan)
date c Current date time representation
date C Century(year/100, truncated to nearest number)
date d Current Day of the month
date e Current Day of the month
date H Current hour of time(00-23)
date I Current hour of time(12 hour clock)
date m Current Month as decimal two digit number
date M Current minute of time(00-59)
date n Newline character
date p AM or PM
33Use Significance
date R Current time as HM
date S Current second of time(00-59)
date t Tab character
date u Weekday as 1 digit number1-7 for Monday-Sunday
date w Weekday as 1 digit number 0-6 for Sunday-Saturday
date V Week number of the year
date x Current date as dd/mm/yy
date X Current time in hhmmss
date y Two digit year
date Y 4 digit year
date Z Time zone name
34Examples of Date
35calendar
- Provides a useful reminder mechanism for the
user. It is a sort of engagement diary. - It searches for the file calendar in the
current directory for lines containing any date
equal to current date or next working date.
Identifies numeric dates as mm/dd/yy. - Other date formats identified are- ltMongt ltdtgt
-
ltMongt ltdtgt , ltyeargt
36 cat calendar I have a meeting on 07/10/2003
with Subhomoy I have a meeting on 08/10/2003 with
Biswajit I have a meeting on 06/10/2003 with
Sugata I have a meeting on 09/10/2003 with my
delivery manager I plan for a dinner on Sep 10,
2003 with my team I have a meeting on
11/10/2003 I have a meeting on 12/10/2003 I will
not come to office on 09/11/2003 calendar I
have a meeting on 09/10/2003 with my delivery
manager I plan for a dinner on Sep 10, 2003 with
my team I will not come to office on 09/11/2003
37who
Show the other persons logged into the system.
Use Significance
who Produces a three columnar output on the users logged in- 1st column shows the userid , 2nd column shows their terminal no. and third one shows the date and time of logging in
who Hu Produces five column output with column headers at the top. The fourth column shos how many minutes the user is idle, fifth column shows the PID of the parent shell for the user.
who am I Produces single line of output pertaining to the user who invoked the command
38who sqian pts/td Sep 9
1827 ems2000 pts/te Sep 10 0141 who
-Hu NAME LINE TIME
IDLE PID COMMENTS sqian pts/td
Sep 9 1827 732 28935 135.148.207.175 ems2
000 pts/te Sep 10 0141 002 29362
129.42.68.104 who am i ems2000 pts/te
Sep 10 0141
39tty
Shows the terminal being used by the user
Example
tty /dev/pts/te
40uname
Know the name of the machine/Version no of the
Operating System
Use Significance
uname n Shows the name of the Unix server being used in the network
uname r Show the version no of the Operating system
Similar command hostname
41uptime
Syntax uptime -hlsuw user
Displays the current time, the length of time the
system has been up, the number of users logged on
to the system, and the average number of jobs in
the run queue over the last 1, 5, and 15 minutes
for the active processors.
Flag Significance
-u Print only the first line describing the overall state of the system. This is the default for the uptime command.
-h Suppress the first line and the heading line. This option should not be used with the -u option. This option assumes the use of the -w option to uptime.
-l Use long output. This option assumes the use of the w option to uptime.
42uptime -u 217am up 122 days, 1103, 2
users, load average 0.41, 0.41, 0.41 uptime
-h sqian pts/td 627pm 739
rlogin htstbw00 ems2000 pts/te 141am
-ksh uptime -l 218am up
122 days, 1104, 2 users, load average 0.40,
0.41, 0.41
43login
Syntax login ltserver name IP addressgt
- Starts terminal session.
- Used at the beginning of each terminal session to
properly identify a prospective user - Can be invoked as an user command also. When used
as a command, the previous terminal session is
replaced. Prompt for userid and password appears.
44telnet
Syntax telnet ltserver name IP addressaliasgt
- Helps to connect to another Unix server connected
to the same network, without being logged out of
the current environment. - If one does not specify a server, a prompt
telnetgt appears. One can use a number of
commands from that prompt.
Commands Significance
open lthostnameIP addressgt Opens a connection to the user
exit Returns to telnetgt prompt after closing connection to the host
quit Exits telnet
45exit
Allows to exit the current shell
Syntax exit
46lock
Syntax lock -ltminutes to lock after logoutgt
- Helps to lock an open terminal to prevent other
people gaining access - When invoked as a command, password has to be
entered and re-entered to confirm it - To unlock the terminal to use it, the user has to
use this password - A locked terminal remains locked for default time
of 30 minutes after which it logs out. To change
the default time- - lock n
- (Terminal remains locked for n minutes, after
which it logs out)
47Example
48script
Syntax script -a ltnewfilegt
- Helps to record login session in a file called
typescript in the current directory. All the
commands, their output and error messages are
stored for later view. - After starting the scripting, user continues with
his job. All the commands he uses, their output
and error messages are stored for later view. - When the user exits from the scripting(writing
exit from OS prompt), the script file is saved
and a message is shown- - Script done, file is typescript
Uses Significance
script a Append activities to existing file typescript
script newfile To log activities to a new file newfile
49Examples
50bc
Binary Calculator for Unix.
bc 12 5 17 d
bc 125 60 d
bc 20/5 4 d
bc 12 - 5 7 d
bc 23 8 d
Addition
Multiplication
Division
Exponential
Subtraction
51Scale- By default, bc performs truncated
division.One have to set scale to the number of
digits of precision before performing any
division.
bc scale2 10/4 2.50 d
If answer to division is greater than the value
as dictated by the scale variable, then the value
dictated by the scale is ignored and the real
value is shown.
52ibase and obase- By default, the input and
output are interpreted as decimal values.But, if
the demand required input and/or output in
different number system(binary, hexadecimal),
variables ibase and obase are set. To convert
binary input to decimal output- ibase2 To
convert decimal input(default) into binary
output- obase2 For hexadecimal systems, value
16 is used in ibase/obase variable.
53Handling Variables- Variables can be used in bc
mode and values can be assigned to them.
bc X12 y19 Zxy Z 31
Conditional logics(if) ,loops(for,while), arrays,
functions are supported by bc
54Square Root of a Number Syntax sqrt ( x
) Example bc Sqrt ( 4 ) 2 Length of a
Number Syntax length ( x ) Example bc length
( 1234.5678 ) 8
55Trigonometric Functions To use trigonometric
functions of bc, one have to include math
library. For that , issue the following command
from Os prompt- bc l Various trigonometric
functions available with bc are-
s(x) sine c(x) cosine e(x)
exponential l(x) log
56expr
Allows to perform calculations and handle strings
Calculations
expr 100 50 150 expr 100 50 50 expr 100 \
2 200 expr 12 / 3 4
expr 12 5 2 zexpr 100 50 50
57String handling
To find length of a string- expr ltstringgt
. Example expr Unix .
4 To extract a substring from a string-
expr Subhendu (\..\) he
Shows 4th to 5th
character To locate first position of a character
in a string- expr Subhendu dh 4
Shows h
is at 4th position
58factor
Finds out factor of the integer provided
Syntax factor ltnumbergt
factor 18 18 2 3 3
factor 15 15 3 5
59primes
Shows all prime numbers between integers ltlower
valuegt and ltupper valuegt. If upper value is not
provided, it is considered to be 2,147,483,647.
Syntax primes ltlower valuegt ltupper valuegt
primes 0 10 2 3 5 7
60units
- Converts quantities expressed in various standard
scales to their equivalents in other scales.
Acts interactively as follows- - System Prompt User Response
- You have inch
- You want cm
- The system responds with two factors one
used if multiplying (preceded by ), the
other if dividing (preceded by /) - 2.540000e00
- / 3.937008e-01
- For a complete list of units, examine the file
- /usr/share/lib/unittab
61tput
Controls screen display
Options Significance
tput clear Clears the screen
tput cup ltrgt ltcgt Moves cursor to row ltrgt and column ltcgt
tput bold Bold display
tput blink Blink display
tput rev Reverse display
tput cols Shows number of columns in the screen
tput bel Echo bell character
tput lines Shows number of lines in the screen
tput smso Starts reverse display
tput rmso Ends reverse display
62Examples
63time
Syntax time ltcommandgt
- Times a command.
- Command ltcommandgt is executed and time prints-
- Elapsed time during the command
- Time spent in the system
- Time spent executing the command
64Example- time grep -i "Subhendu"
ABCDEFsubhendu bounce_off.ksh Developed by
SUBHENDU MAJUMDAR drawbox.ksh
Developed by SUBHENDU MAJUMDAR header
Developer SUBHENDU
MAJUMDAR heading Developer
SUBHENDU MAJUMDAR real 6.6 user
0.8 sys 0.7
65Handling Files
This section will introduce you with
Architecture
Cat Create,View, append Files
file know file type
Types of Files
VI Visual Editor
chmod Change permissions
Inode
more display files
chown Change owner
File System
pg View files
chgrp Change group
pwd-Current Directory
cp,mv Copy and rename files
touch Change time stamp of a file
cd Change Directory
rm Remove Files
ln Link a file to other
ls List contents of a dir
wc Count word,line and characters
66Handling Filescontd
dircmp Compare Directories
mkdir Create Directory
lp Print a file in a printer
rmdir Remove Directory
lpstat View printer status
cmp compare two files
cancel Cancel print jobs
comm Compare two files
pr Format file contents
sdiff find differences between two files
Compressing and Uncompressing Files
67File maintenance architecture
Formatted Disk
Partition
Partition
Partition
File system
Directory
Directory
Directory
Directory
Directory
Directory
File
File
File
68Types of Files
Normal files Can be text/binary files. Can be a
text file, compiled source code ,
executables Directory files Contains no external
data, but details of files and sub-directories it
contains. Device files Printers, tapes, floppy
drives, CD ROMs, hard disks, terminals all are
considered as files
69Inode
- Inode is a fixed format structure containing the
attributes of the files stored in the file
system. - Every file has one inode, and a list of such
inodes is kept in a disk area not directly
accessible by user. - Each inode is accessed by inode number,
specifying the position of the inode in the list.
70Some of the important information that inode
contains are-
Information Significance
Mode Permission mask and type of file
Link count No. of links associated with the file
User id ID of the owner
Group Id ID of the group
Size No. of bytes in the file
Access time Time of last access of the file
Mod time Time of last modification of the file
Inode time Time at which the inode structure was last modified
71Typical File System
/ (root)
Unix
bin
dev
usr
tmp
etc
bin
usr1
usr2
usr3
/Unix folder contains the kernel /bin contains
binary executable files /dev contains device
related files /usr is the home directory for all
users /usr/usr1 is the home dir. for user usr1
/tmp contains temporary files /usr/bin contains
additional binary unix commands /etc contains
binary executable files for system administration
72pwd
Shows the directory where the user is currently
in
Syntax pwd
- Example
- pwd
- /home/ems2000
73cd
Navigates from the current directory to another
directory
Syntax cd ltnew directory specificationgt
Commands Significance
cd scripts cd ./scripts Moves to directory scripts under current working directory
cd ../program Change to directory program residing in the current directory's parent directory
cd /usr/fin/subhendu/ manfiles Change to the directory whose absolute pathname is /usr/fin/subhendu/ manfiles
cd cd Move to home directory of the user
74Commands Significance
cd .. Move to the parent directory of the current working directory
cd /subhendu Move to folder subhendu under the home directory for the user
75cdpath
This is an environmental variable which specifies
the list of directories to be searched when an
user issues a cd command.
CDPATH...HOME This means, when a cd
command is issued, search for the new directory
first in current working directory(.) If not
found, move to the parent directory of the
current directory and search there. If, still,
not found, search for the directory under users
home directory
76ls
Shows the contents of a directory/existence of
specific files with their attributes
Syntax ls flag string for filename
Commands Significance
ls Shows the name of all the files and directories under the current directory, excluding those starting with .
ls a Lists all files including those starting with .
ls x Multi columnar output
ls R Shows all files and recursive listing of all files in sub-directories
ls l Long listing showing seven attributes of a file
ls F Marks executables with and directories with /
77Commands Significance
ls t Sorts files by modification time the file modified most recently comes at the top
ls ut Sorts files by access time
ls r Sorts file in reverse order
ls ltr Shows long listing of files with their attributes, sorted in reverse order by access time(most recently edited file comes last in the list)
ls i Shows inode number of a file
ls .ksh Shows the name of all files with .ksh at the end of their name
ls aeiou Shows the files with name starting with vowels
ls d.sh Lists all files starting with d and ending with .sh in their name
ls d?l Lists all files with first letter as d and third letter as l
ls !aeiou Shows the files with names not starting with vowels
78(No Transcript)
79(No Transcript)
80(No Transcript)
81cat
Creates , shows, concatenates,copies files
Commands Significance
cat gtfile1 Creates file file1 where a user enters text and presses ltCtrl-Dgt to end text editing
cat gtgtfile1 Append lines to existing content of file file1 and is ended when ltCtrl-Dgt is pressed
cat file1 Shows the contents of the file file1
cat file1gtfile2 Copies the contents of file file1 into new or existing file file2
cat file1 file2 gt file3 Concatenates the content of file1 and file2 and places it into new or existing file file3
cat file1 gtgtfile2 Appends the contents of file1 after the last line of file2. If file2 does not exist, new file is created
82Commands Significance
cat n file1 Displays the contents of file file1 with line number
cat b file1 Displays the contents of file file1 with line number for all lines excepting the blank lines
cat e file1 Prints at the end of each line
cat r file1 Replaces multiple consecutive empty lines with one empty line
cat t file1 Prints tab character as I and form feed character as L
cat s file1 file2 gtfile3 Suppresses error and does the job. If file file2 does not exist, the command will copy the contents of file1 into file3
83Examples
84Examplescontinued
85Examplescontinued
86VIFirst Unix Full screen Editor
87First full screen editor, developed by
William(Bill) Joy, a graduate student from
University of California, Berkley.
- Divides Unix users into two camps
- Those who hate vi
- Those who love vi
Haters say that it is the worst thing ever
happened in the Unix world. Lovers are totally
biased towards it and would go any length
supporting its cause.
88Modes of Operation
Ex mode
First session with vi
Environmental variables
.exrc EXINIT variable
Append mode
Command mode
view
89Mode of Operation
Command mode Default mode when a file is opened
using vi. All the keys pressed by the user are
interpreted as user commands
Append Mode Permits insertion of new text,
editing existing texts.
Ex mode Permits commands at the command
line(last line of the screen)
90Command Mode
R,R,I,I,c,C,o,O,s,S,a,A
Enter
Esc
Append Mode
Ex Mode
91First Session with vi
92Step 1 Create a new file by typing the
following command from the OS Prompt vi newfile
- vi clears the screen and display a window.
- The _ on the top line indicates that the cursor
is waiting for commands - Every other line starts with , symbol for
empty line.
93Step 2 Press i to enter into Append mode. Add
text to the file
Step 3 Press ltEscgt key to return to command mode
94Step 3 Press . The cursor takes to the ex
mode at the command line. Enter wq and press
enter.
95Append Mode
Inserting Texts
Cmd Significance
i Appends text from the left of the current cursor position
I Appends text at the start of the current line.
a Appends text from the right of the current cursor position
A Appends text at the end of the current line.
o Opens a line immediately below the current line in input mode
O Opens a line immediately before the current line in input mode
96Changing Texts
Cmd Significance
ltngtr Replaces ltngt characters from current cursor posn. with inserted text
R Replaces text from cursor to right
ltngts Replaces ltngt characters from cursor with entered text
ltngtS Replaces ltngt lines from the current cursor line with entered text
c0 Changes from cursor to beginning of line with the text entered
c Changes from cursor to end of line with the text entered
C Change from current cursor posn. to end of line with the text entered
ltngtcw Changes ltngt words from the current cursor position with text entered
ltngtcc Replaces ltngt lines from the current cursor line with entered text
cG Changes from current cursor position to end of the file with entered text.
97Command Mode
Saving work in a file and quit
Cmd Significance
ZZ Saves the work done in the file and quits editing by vi editor
Deleting texts/lines
Cmd Significance
ltngtx Deletes ltngt characters from current cursor position
ltngtdd or ltngtD Deletes ltngt lines counting from current cursor line to below
d Deletes from current cursor position to end of line
dG Deletes from current cursot position to end of file
dltngtG Deletes from current line to line no ltngt
dfltchargt Deletes from current cursor position to first occurrence of character ltchargt
d/ltpatterngt Deletes from cursor upto the first occurrence of string ltpatterngt in forward direction
d?ltpatterngt Deletes from cursor upto the first occurrence of string ltpatterngt in backward direction
98Moving/Copying Texts
Cmd Significance
ltngtyy or ltngtY Yank ltngt lines starting from current line onwards into undo buffer
ltngtyw Yank ltngt words starting from current cursor position onwards into undo buffer
y Yank from current cursor position to end of the line in undo buffer
yG Yank from current cursor position to end of the file in undo buffer
altngtyy Yank ltngt lines starting from current line onwards into buffer named a
p Paste the contents of undo buffer( as a result of deleting or yanking) after the cursor position
P Paste the contents of undo buffer( as a result of deleting or yanking) before the cursor position
ap Paste the contents of buffer a after the cursor position
bd Delete text into named buffer b
99Navigation in same line
Cmd Significance
ltngth Moves cursor left to nth previous character w.r.t. the current cursor position
ltngtl Moves cursor right to nth next character w.r.t. the current cursor position
ltngtb Moves cursor left to start of nth previous word w.r.t the current cursor position. Punctuation marks are taken into account.
ltngtw Moves cursor right to start of nth next word w.r.t the current cursor position. Punctuation marks are taken into account.
ltngte Moves cursor right to end of nth next word w.r.t the current cursor position. Punctuation marks are taken into account.
fltchgt Move the character to the next character ltchgt on same line
Fltchgt Move the character to the prv. character ltchgt on same line
tltchgt Move the character to one column before the next character ltchgt on same line
Tltchgt Move the character to one column after the next character ltchgt on same line
Repeats search in the same direction along which the prv. Search was made using f/t
100Cmd Significance
, Repeats search in the opposite direction along which the prv. Search was made using f/t
ltngt Moves the cursor to specified column ltngt
0 or ( Moves to 1st character of the current line
or ) Moves to last character of current line
Moves to 1st non-space character of the line
ltngtB Moves cursor left to start of nth previous word w.r.t the current cursor position.Punctuation marks are ignored
ltngtW Moves cursor right to start of nth next word w.r.t the current cursor position. Punctuation marks are ignored
ltngtE Moves cursor right to end of nth next word w.r.t the current cursor position. Punctuation marks are ignored
101Navigation across lines
Cmd Significance
ltngtj or ltngtn Move the cursor down to the ltngtth next line in the same column
ltngtk or ltngtp Move the cursor up to the ltngtth prv line in the same column
H Moves the cursor to the top line of the screen
L Moves the cursor to the last line of the screen
M Moves the cursor to the middle line of the screen
ltngtG Moves to line number ltngt
Moves the cursor to next lines first non-blank character
- Moves the cursor to previous lines first non-blank character
102Redraw screen
Cmd Significance
z- Makes the current line the last line of the screenand redraws the screen
z Makes the current line the first line of the screenand redraws the screen
z. Makes the current line the middle line of the screenand redraws the screen
Ctrl-l Redraws the screen
/pattern/z- Find the next occurrence of ltpatterngt and make that last line of the screen
103Scrolling across pages
Cmd Significance
ltngtf Move forward by ltngt screens
ltngtb Move backward by ltngt screens
ltngtd Move forward by ltngt number of half screens
ltngtu Move backward by ltngt number of half screens
ltngte Scroll window down by ltngt lines
ltngty Scroll window up by ltngt lines
104Pattern searching
Cmd Significance
/pattern Searches for specified ltpatterngt forward. IF end of file is reached, search wraps around.
?pattern Searches for specified ltpatterngt backward.
n Repeat the last search in the same direction as was specified in the last search
N Repeat the last search in the opposite direction as was specified in the last search
/pattern/ltngt Positions the cursor ltngt number of lines after the line where the specified ltpatterngt is found
/pattern/-ltngt Positions the cursor ltngt number of lines before the line where the specified ltpatterngt is found
Find the matching braces or parenthesis
105Joining lines
Cmd Significance
ltngtJ Joins current line and ltngt lines below it together to form a single line
Undo changes
Cmd Significance
u Undo last change
U Undo all the changes in the current line
Marking text
Cmd Significance
mltchargt Marks position of the file with mark ltchargt
ltchargt Moves to portion of the file marked with ltchargt
Toggle to most recently marked location
106Restoring previously deleted line
Cmd Significance
ltngtp Paste the content of ltngtth last delete ( nlt9)
1pu.u.u Till the last change is found
Filtering texts
Cmd Significance
!ltngtG sort Sort from current line to line no. ltngt
!ltngtG tr a-z A-Z Translates all the characters from current line to line ltngt to uppercase
!! tr a-z A-Z Translates all the characters of current line to uppercase
Repeat factor
Cmd Significance
ltngtiltchgt Inserts ltchgt character ltngt number of times in input mode at a stretch
107Miscellaneous in command mode
Cmd Significance
Change the character under cursor from lowercase to uppercase and vice versa
. Repeat the last change
ltngt. Repeat the last action n times
ltlt Shift current line to shift width character left
gtgt Shift current line to shift width character right
108Options available with vi command
Cmd Significance
vi r ltfilenamegt Recover the file ltfilenamegt as much as possible after system crash and open it
vi R ltfilenamegt Open the file ltfilenamegt in read-only mode
vi ltngt ltfilenamegt Opens the file ltfilenamegt with cursor positioned in line number ltngt
vi ltfilenamegt Opens the file ltfilenamegt with cursor at the last line
vi wltngt ltfilenamegt Opens file ltfilenamegt in vi mode with window size of ltngt number of lines
vi /ltpatterngt ltfilenamegt Opens file ltfilenamegt in vi editor and places the cursor at first occurrence of pattern ltpatterngt
vi x ltfilenamegt Opens encrypted file ltfilenamegt in vi mode and asks for the password before opening that
109Ex Mode
Saving work in a file
Cmd Significance
w Save the changes made to the file
w ltfilenamegt Same as Save As.. in windows. Saves the contents to the specified file ltfilenamegt . If it does not exist previously, a new file is created
w! ltfilenamegt Save the changes to file ltfilenamegt, if the file already exists
w gtgt ltfile1gt Append the contents of the opened file after the last line of the file ltfile1gt. File ltfile1gt should exist previously
ltn1gt,ltn2gtw ltnewfilegt Copies the contents of lines ltn1gt to ltn2gt into a new file ltnewfilegt
ltn1gt,ltn2gtw! ltnewfilegt Moves the contents of lines ltn1gt to ltn2gt into an existing file ltnewfilegt , overwriting its previous contents
110Cmd Significance
.,.ltngtw ltnewfilegt Appends from current line to ltngt number of lines below it into file ltnewfilegt
.,.ltngtw gtgt ltnextfilegt Appends from current line to ltngt number of lines below it after the last line of the file ltnextfilegt
q Quits the file editing in vi, provided no unsaved change remains
q! Quits vi neglecting all the unsaved changes made to the file
wq or x Save the unsaved changes in the opened file and quit vi editor
Temporary exit to shell
Cmd Significance
sh Temporarily allows the user to come out of the vi file and use the shell. After the job of the user is done and command exit is triggered from OS prompt, control returns to vi editor again
111Navigating to desired line
Cmd Significance
ltngt Custor moves to line number ltngt
Search and replace texts in ex mode
Syntax - ltline addressgts/ltold patterngt/ltnew
patterngt/g
Line address Significance
All lines where matching pattern is found
. Current line
ltn1gt,ltn2gt Refers from line ltn1gt to ltn2gt
Last line
1, First to last line
.,.ltngt From current cursor line to ltngt number of lines downwards
112Examples of Search and Replace
Example Significance
s/ex/vi/c Substitutes 1st occurrence of string ex with vi by showing them and asking for confirmation. When each string will be shown with pause in cursor, press y for substitution
s /ltamaze \ gt\/delight/g Replaces amaze , where available as a full word, with delight. Note, any word like amazed will not be replaced
g/subhendu/s/majumdar/mazumder/g Replaces every occurrence of string majumdar with mazumder on all lines containing the pattern subhendu
g/.\ 9\ 9/s/0//g Replaces 0 with at all lines having 9 after 9th position
g//d Delete all blank lines
g!/complete/s//To be done/ Append the string To be done at the end of all lines not containing the string complete
113Example Significance
g/vi/s//editor/ Append the string editor at the first of all lines containing the string vi
s// see my note/g Appends the string see my note at the end of all lines
g/./d Deletes all lines containing 4 letters
g/..o/d Deletes all lines with o as 3rd character
s///g Delete the last three character of every line
Reading below the current line in the vi editor
Command Significance
r ltnextfilegt Reads the contents of the file ltnextfilegt below current line
r! ltcommandgt Places the output of the command ltcommandgt below the current line
114Editing another file
Command Significance
e ltnextfilegt Stops editing the current file leaves the current file and starts editing file ltnextfilegt provided there are no unsaved changes in the current file
e! ltnextfilegt Edits file ltnextfilegt abandoning all the changes done to the current file
e! Loads last saved version of current file
n Edits next file mentioned in the vi queue
rew Edits first file in the command line
e ltngt ltnextfilegt Edit starts at line ltngt of file ltnextfilegt
115Abbreviating texts
Command Significance
ab ltshort_stringgt ltlong_stringgt When the user writes the string ltshort_stringgt in input mode, the ltlong_stringgt is written
Mapping
Command Significance
map g wM Pressing g, one wants to save the file(w is for saving, and M is for pressing Enter key. While writing it in the command line, write VM)
map z iM When you position your cursor to any character in a line and press z , the line will be broken from that point and two lines will be formed. The control will remain in command mode ( represents ltEscapegt key)
map z wM!M Pressing z in command mode saves the file and executes it in one shot
To unmap a key, write at the command line unmap
ltkeygt
116Miscellaneous
Command Significance
! ltcommandgt Executes the command ltcommandgt remaining in vi editor
f Shows the name of the current file and line
g Same as f
117Setting environmental variables for vi
Works in ex mode. To set an environment variable
to customize vi, the following syntax needs to be
followed- set ltenv.variablegt ltvaluegt
118Environment variables Significance
autoindent(ai) Newly inserted lines of text are indented to the same distance from left margin as the preceding line. Opposite of this option is noautoindent(noai)
autowrite(aw) Automatically saves the unsaved changes in a file before opening the next file with n or using a shell command with ! ltcommandgt. The opposite to this option is noautowrite(noaw)
errorbells(eb) Sounds the bell when error occurs. Opposite is noeb
exrc(ex) Allows an .exrc file in the current directory to override the .exrc file in users home directory. Opposite is noex
list Displays special characters in the screen tabs are shown as I, end of line are marked with . Opposite is nolist
mesg System messages allowed when vi is running. Opposite is nomesg
number( nu ) Displays line numbers. Opposite is nonu
119Environment variables Significance
reportltvalgt When any operation affects more lines than this settings, message is displayed
scrollltvalgt Number of screen lines to scroll
shiftwidth(sw)ltvalgt Number of spaces to be used for backtabs/ltlt/gtgt
showmatch(sm) Shows match for ) or . Opposite is nosm
showmode Indicates type of mode
tabstopltvalgt No. of spaces the tab character moves over
ignorecase(ic) Ignores case when searches patterns. Opposite is noic
wrapmargin(wrm)ltvalgt When set to a value gt0 , carriage returns are inserted automatically when the cursor gets to within that number of spaces from the right edge of the screen
120.exrc file and EXINIT system variable
One can store all the values for environment
variables, all the key mappings and all the
abbreviations in a file .exrc under the home
directory for the user.VI looks for this file on
startup and executes the instructions as ex mode
commands. Besides, there is also a system
variable , EXINIT which can also be used to
save the settings. EXINITset report5
ignorecase ai export EXINIT
121view
Syntax view ltfilenamegt
Description Shows the file ltfilenamegt in vi
mode. File remains read-only. No changes done to
the file cannot be saved.
122more
Syntax more -n ltnumbergt -ltnumbergt -d
-i -e -c -f -s /pattern filename
- Filter for examining continuous text, one
screenful at a time. It pauses after each
screenful,printing the filename at the bottom of
the screen. - To display one or more next lines, press ltReturngt
- To display another screenful, press ltSpacegt
123Command line option Significance
-n ltnumbergt Sets the no of lines in the display window to that ltnumbergt.
-ltngt Same as above
-d Prompts user with message - Press space to continue, q to quit, h for help at the end of each screenful of display
-i Performs case independent pattern matching
-c Draw each page by starting at the top of screen, and erase each line before drawing on it
-s Squeeze multiple blank lines from the file , showing only one blank line
/pattern Start listing such that the current position isset to two lines above the line matching the regular expression pattern.
124Internal commands in more mode
Options Significance
f Scrolls forward one screen
b Scrolls backward one screen
q Quit
/pattern Searches pattern ltpatterngt forward
?pattern Searches pattern ltpatterngt backward
v Opens vi mode for the file viewed
n or N Repeats last search
ltngtj Scrolls forward by ltngt number of lines
ltngtG Moves to line number ltngt
G Goes to last line of the file
. Repeats prv. command
n Moves to next file specified in the command line
125Options Significance
p Moves to previous file specified in the command line
iltspacegt Scrolls forward by i number of screens
iltreturngt Scrolls forward by i number of lines
ltigtd/ ltIgt Scrolls forward i lines, with a default of ½ of the screen size
ltigtu /ltigtu Scrolls backward i lines, with a default of ½ of the screen size
ltngtk/ ltngty Scrolls backward by ltngt number of lines
ltngtz Displays ltngt more lines and sets the window size to ltngt
ltngtf / ltngtf Moves forward by ltngt lines
ltngtb / ltngtb Moves backward by ltngt lines
g Writes the name of the file currently being examined, the no. relative to the total number of files to be viewed, the current line no,current byte no, total no of bytes to write and what of the file precedes the current position
126Options Significance
h Display a descriptive list of all the more commands
!ltcommandgt Invoke a shell with a command ltcommandgt
e ltnewfilegt Leaves the current file and starts viewing a new file ltnewfilegt
ltIgtn Examines the ltIgtth next file specified in the command line
r / l Refreshes the screen
. Repeats the prv command
mltchargt Marks the current position with letter ltchargt
ltchargt Returns to the position previously marked by the specified letter ltchgt
127pg
Displays the content of a file one page at a time
Syntax pg lt flag and stringgt ltfilename(s)
Flag Significance
-c Clear the screen at the end of each page of display and start the display at the top of the screen
-e Continues to the next file after the end of one file, if more than one files are specified at the command line
-f Truncate lines longer than the width of the screen display
-p ltstringgt Display the ltstringgt at the pg command prompt.Default is . If string is d the pageno is displayed atr the prompt
-s Highlights all messages and prompts issued by the pg command
ltngt Start the display from line no ltngt of the file specified
128Flag Significance
-ltngt Sets the size of the display screen to ltngt number of lines
/pattern/ Search for pattern ltpatterngt in the file and start the display at that line
Keystrokes in pg mode
Option Significance
-ltngt Go backward by ltngt number of pages
ltngt Go forward by ltngt number of pages
l Go forward by one line
ltngtl Start the display in the file at line specified by ltngt
ltngtl Go forward by ltngt lines
-ltngtl Go backward by ltngt lines
d Go forward by ½ screen
-d Go backward by ½ screen
l Redraws the screen
129Option Significance
Move to last page of the file
ltngt/ltpatterngt Searches forward for the pattern ltpatterngt in the file from beginning of the next page. If a number ltngt is specified, pg searches for the specified occurrence number ltngt of the ltpatterngt
ltngtp Starts showing the ltngtth previous file.
n Start showing the next file
q Quits the pg command
130cp
Copies one file to another file/one directory to
another directory/files into directories
Syntax cp -flag old files/directories new
files/directories
Flag Significance
-i Interactive copying prompt appears for user accent before copying
-f Force copying
-p Preserve permissions. Preserves modification time,access time,file mode, user id, user group etc
-r Recursive copying
131Examples
Example Significance
cp file1 file2 Copies the contents of file1 into new or existing file file2
cp file1 file2 file3 dir1 Copies files file1, file2 and file3 into directory dir1
cp R dir1 dir2 Copies directory dir1 into a new directory dir2(if dir2 does not exist before) / copies the directory dir1 as a sub-directory under dir2(if directory dir2 exists before)
cp R dir1 dir2 dir3 If dir3 exists, two sub-directories under it are created dir1 and dir2. IF dir2 directory does not exist, then a new directory dir2 is created with the contents same as dir1 and one additional sub-directory dir2
132mv
Syntax mv -flag old files/directories new
files/directories
Moves/renames- A file to new or existing
file One/more files to existing directory One or
more directories to a new or existing
directory. If the access permission of the
destination directory or existing destination
file forbids writing, mv command asks for
overwriting the file
Flag Significance
-f Performs move operation without prompting for permission
-i Interactive moving
133rm
Syntax rm -f-i -r-R filesdirectories
Removes the entries for one/more files from a
directory. Destroys the file whose last link is
deleted Removal of a file requires write
permission for that file Removal of a file from a
directory required write and execute permission
in the directory
Flag Significance
-f Forceful deletion
-i Interactive deletion
-r or R Recursively delete the entire contents of the cirectory before removing the directory itself
134Examples
Example Significance
mv .txt ../testdir Moves all the files with .txt extension under the directory testdir residing under the parent directory of the current directory
rm .temp Remove all files with extension .tmp under the current directory
rm r backupdir Remove the directory backupdir with all its contents
135wc
Syntax wc -c-l-w ltfilename(s)gt
Counts the number of words/bytes/characters/lines
in a file
Flag Significance
-w Counts the total no. of words
-l Counts the total no. of lines
-c Counts the total no. of characters
Examples
wc c file1 32 file1
wc l file1 2 file1
wc w file1 8 file1
136file
Syntax file -f ffile -h file ...
Determines the file type of a file or list of
files. Performs a series of tests on each file
in an attempt to classify it. If file appears to
be an ASCII file, file examines the first
512bytes and tries to guess its language. File
/etc/magic is ued to identify files that have
some sort of magic number, that is, any file
containing a numeric or string constant that
indicates its type. Commentary at the beginning
of /etc/magic explains the format.
137chmod
Syntax chmod file permission
ltfilesdirectoriesgt
A file can have three type of permissions- Read
Authorized user can read the contents of the
file. Write Along with read permission, it
allows the allowed user to modify its
contents. Execute If the file is an executable,
any allowed user can execute it
138A file can be accessed by- User Person
creating the file. He grants all the
authorizations to the file Group Group user for
the file Others All other users not belonging to
the group or are not the creator.
Numeric representation of permissions
Value Significance
4 Read permission
2 Write permission
1 Execute permission
6(42) Read and write permission
7(421) Read,write and execute permission
5(41) Read and execute permission
139Example of granting numeric authorization
Syntax chmod ltval1gtltval2gtltval3gt
ltfilename(s)directory name(s)gt
val1 is for users val2 is for group val3 is for
others Any permission on a directory percolate
down to the files and sub-directories under it.
Example Significance
chmod 744 file1 Grant all permissions to User, and read permission to group and others
chmod 776 Grant all permission to user and group, read and write permission to others
chmod 777 file1 Grant all permission to all
140Alphabetic representation of permissions
Value Significance
r Read permission
w Write permission
x Execute permission
Value Significance
u User creating the file
g Other users in the same group of the creator
o Any other users
a All(creator, other users in the same group, and other users)
141Example of granting alphabetic authorization
Example Significance
chmod urwx,gor file1 Assign read,write and execute permission to user, but only read permission to group and others
chmod o-x file1 Revoke execute permission from others
chmod ax file Assign execute permission to everybody
chmod R ugr,o-r,ax /home/ems2000 Traverse the directory subtree under directory /home/ems2000 making all regular files readable by user and group only, revoke read permission from others and grant execute permission to all
142Chown and chgrp
Syntax chown -h -R owner file
chgrp -h -R group file
chown changes owner of the file and chgrp changes
group of each file specified. To change user or
groyp, one must own the file and have the CHOWN
privilege granted to him by the system
administrator
Options Significance
-h Change owner/group of a symbolic link
-R Recursively change the owner and group of all the files and sub-directories under the directory named
143Example Significance
chown ems2000 auto.profile User ems2000 becomes the owner of the file auto.profile
chgrp ems2000 auto.login User ems2000 becomes the group user to access the file auto.login
chown R ems2000 users shell_scripts The command searches the directory shell_scripts and changes each file in that directory to owner ems2000 and group users
144touch
Updates access time/modification time of file(s)
Syntax touch -amc -r ltref-filegt -t
lttimegt ltfilename(s)gt
Flag Significance
-a Change the access time of the file to the time specified/ if no time is specified, use the current time
-m Change the modification time of the file to the time specified/ if no time is specified, use the current time.
-r ref-file Use the corresponding time of file ref-file to change the modification/access time of the file
-t lttimegt Use the specified time lttimegt instead of current time. The time format is ltYYYYgtltMMgtltDDgtlthhgtltmmgt.ltssgt
145Example Significance
touch a wot.ksh Changes the access time of wot.ksh with the current date and time (Changes can be perceived if the command ls ut is fired in the directory containing the file the file wot.ksh will come at the top of the list)
touch m wot.ksh Changes the modification time of wot.ksh with the current date and time (Changes can be perceived if the command ls lt is fired in the directory containing the file the file wot.ksh will come at the top of the list)
touch -m -t 201012122300 new.del Changes the modification time of file new.del to Dec 12,2010 time 2300 Seeing the attributes of the file new.del will reveal the information- -rw-rw-r-- 1 ems2000 dba 10 Dec 12 2010 new.del
touch -m -r new.del new1 Change the modification time of file new1 and make it same as the modification time of the file new.del
146ln
Description Link files and directories
Command Significance
ln -f-i file1 newfile Links file file1 to a new or existing file file1
ln -f-i file1 file2 testdir Creates link for files new1 and new2 under the directory testdir with two new files/existing files new1 and new2
ln -f-i dir1 dir2 testdir Creates link for directories dir1 and dir2 under the directory testdir with two new /existing directories dir1 and dir2
Flag Significance
-f Force esisting files or directories to be removed to allow the link
-i Interactive linking
147mkdir
Creates directories
Syntax mkdir -p -m ltmodegt ltdirectory
name(s)gt
Flag Significance
-p Intermediate directories are created as necessary.Otherwise, the full path prefix of dirname must already exist. mkdir requires write permission in the parent directory.
-m ltmodegt Mode of permission for the directory and all the files under it
148Example Significance
Mkdir m755 testdir Directory testdir is created with permission 755
mkdir p testdir/subhendu If testdir is not created, it is first created. Then, a directory subhendu is created under the directory testdir
149rmdir
Removes the directory entry for each empty
directory referred
Syntax rmdir -f-I-p ltdirectorygt
Flag Significance
-f Forcefully remove a directory, even though it is not empty
-i Interactive removal of empty directory
-p Path removal.If, after, removing a directory with more than one pathname component, the parent directory of that directory is empty, rmdi