Skip site navigation (1)Skip section navigation (2)
Date:      Tue, 16 Sep 2008 15:05:21 -0700 (PDT)
From:      johnharten <Boston.Jung@gmail.com>
To:        freebsd-ports@freebsd.org
Subject:   Linux Help
Message-ID:  <02a63bf9-fa84-4dba-a5c9-94053332584f@j22g2000hsf.googlegroups.com>

next in thread | raw e-mail | index | archive | help
LINUX is not UNIX, but it's close enough
This book is old
I will try to take the concepts the book lays out and integrate them
with more recent versions.
Lecture material will be a hybrid
Chapter 1

Logging on to the System
Why we study UNIX/LINUX
Started in the 1970's (pre-Microsoft)=FE
UNIX runs =93everything=94
The Internet, Stock Market, Movies, technological advancements,
Embedded Devices (ATM's), POS systems, the military, utility
companies, and much more.
Linux began in the early '90's
Has revolutionized the IT world
Authentication
Authentication is the process of confirming that you are who you say
you are
Logging in (authenticating) typically requires two components
Username (login name)=FE
Password
Authentication (continued)=FE
Authentication can also take the following forms:
Public/Private Key Pair
PGP / SSL certificates
Biometric Authentication
Fingerprints
Retinal scans
Voice matching
Authorization
Authorization is the process of determining who gets access to what.
Unlike authentication, authorization does not generally involve and
additional input.
Keeps the system secure.
Login Scenarios
Running system with the root username and password
Running system where you have the username / password of non-root user
A system with no Operating System
Scenario:  No OS
If there is no operating system present, you'll need to install one
Setting the root password is part of the installation process
You'll need to create a regular user account for yourself as well
Scenarios:  Have Credentials
Running system where you have a valid username / password (root or
otherwise)
At login prompt, enter valid username and hit enter
At password prompt, enter valid password and hit enter
Have Credentials (cont'd)=FE
Whether or not you enter the username correctly, you will be prompted
for a password.
When you type your password, the characters will be masked by *'s for
security
UNIX is case-sensitive!!!
Notes on root user
root is the system administrator
root has access to all resources and there is no safety net
Use root only when necessary
Login Prompts
Command Line
Telnet / ssh / no graphical environment
Graphical
X Windows system is installed on system
Pictures of both on page 5
Lab Work
Install Linux
Fedora 9, because we have new hardware.

CMPSC 249:

Introduction to UNIX/Linux
Week 2: UNIX Essentials
The Kernel
The kernel is the core of an operating system.
Source Provided for compilation.
RedHat provides RPM packages.  (rpm =96qa |grep =96i kernel)
You don=92t touch it directly.
Where is the Kernel?
The boot loader runs and loads the kernel based on the choice you
make.
Editing the boot loader entry will reveal the location of the kernel
(usually /boot/vmlinuz*)
RamDisk and kernel load and then process id 1 (init) is spawned.
User Space
User space is the visible part of the operating system.
User processes
Services / daemons
Every user space component executes system calls and spends some time
in the kernel.


What does the Kernel do?
Sits between programs (user space) and hardware.
Applications use syscall facilities to have the kernel perform work on
their behalf.
This work takes many forms.

Kernel
Kernel (2)
System call facility that allows processes to use kernel functions.
Process creation and tracking
Process priority control
Swapping pages & memory management
IPC - inter-process communication
Cache, Buffer and I/O management
File creation, removal and modification and permissions
Filesystems
Log file data accumulation and flushing.

The Filesystem
What is a filesystem?

<geek>a method for storing and organizing computer files and the data
they contain to make it easy to find and access them.</geek>
What is a filesystem (English)
A container for data
More than just a place to keep files
Hierarchical
File Attributes
Security

Filesystem Layout
/ =3D System Top Level Directory. Start of the tree
Everything is hierarchical in folders underneath / (/opt, /usr, /etc)
Folders can act as mount points for local and network filesystems
Common Directories
/usr =96 shared, read-only libraries and binaries.
/etc =96 machine configuration files
/home =96 user directories (private)
/boot =96 location of necessary files for boot loader.  Usually at
beginning of disk
Common Directories (2)
/dev =96 location of special device descriptor files
/proc =96 Virtual filesystem that gives insight into the kernel and
running tasks.
/var =96 Typical location of spool (print, mail) and log files.
/opt =96 optional installed packages
/dev and /proc are virtual file systems
Separation of FileSystems
Separation involves creating individual filesystems for each mount
point.
Prevents an errant process or user from filling up all filesystems and
crashing the system.
Separating everything is not practical.

Disk Partitioning
Very similar to Windows, Linux supports carving of drives into
partitions.
During our install we created separate partitions for various
filesystems
The fdisk command can be used to create and view partitions.
To view current disks and partitions use fdisk =96l

Disk Partitioning (2)
Disk /dev/sda: 80.0 GB, 80000000000 bytes
255 heads, 63 sectors/track, 9726 cylinders
Units =3D cylinders of 16065 * 512 =3D 8225280 bytes
   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *           1          32      257008+  83  Linux
/dev/sda2              33        1307    10241437+  83  Linux
/dev/sda3            1308        1568     2096482+  82  Linux swap /
Solaris
/dev/sda4            1569        9726    65529135    5  Extended
/dev/sda5            1569        1600      257008+  83  Linux
/dev/sda6            1601        2875    10241406   83  Linux
/dev/sda7            2876        9726    55030626   8e  Linux LVM
[root@reboot ~]#

Disk Partitioning (3)
To match partitions to filesystems you can use df to correllate:
 [root@reboot ~]# df
Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/sda6              9920592   1463072   7945452  16% /
/dev/sda5               248895     17297    218748   8% /boot
tmpfs                   479236         0    479236   0% /dev/shm
/dev/mapper/vg_reboot-lvhome
                      19838052  16125436   2688616  86% /home
/dev/mapper/vg_reboot-lvtmp
                       9560920     72440   9010156   1% /tmp
/dev/mapper/vg_reboot-lvusr
                       6983168   4129136   2493612  63% /usr
/dev/mapper/vg_reboot-lvvar
                       2951952    701460   2098124  26% /var

LVM
LVM (Logical Volume Management Devices)
Volume Groups are essentially logical disks that can actually span
multiple devices.
/dev/mapper entries are logical volumes within a volume group.
Volume groups can consist of partitions on disks or whole disks called
physical volumes.
Physical volumes (pv=92s) are raw LVM devices with a partition type of
8e or Linux LVM.
=93vgdisplay=94 command lists current lvm volume groups.  With no options,
it prints a stanza for each defined volume group (vg)
[root@reboot ~]# vgdisplay
  --- Volume group ---
  VG Name               vg_reboot
  =85


LVM (continued)
Vgdisplay gives other useful information as well:
PE Size               32.00 MB
Total PE              1679
Alloc PE / Size       1239 / 38.72 GB
Free  PE / Size       440 / 13.75 GB

PE=92s are Physical Extent.  It=92s the smallest allocation size you can
have in a VG.
Total PE is the number of PE=92s in the volume group.
You multiply PE size by Total PE to get the size of the vg.
Allocated PE is the total amount of PE assigned to a volume
Free PE is the total amount of PE that is available for use.
LVM Part 3
How do you determine how many devices are contained in a vg?
Easy =96 you use vgdisplay =96v.  At the very bottom of the output will be
a stanza for each physical volume.

 --- Physical volumes ---
  PV Name               /dev/sda7
  PV UUID               YDgW5U-0gFQ-kzBm-HJh5-0l7F-V1Cp-X7VPcj
  PV Status             allocatable
  Total PE / Free PE    1679 / 440


LVM 4
So, we have pv=92s and vg=92s =96 what about filesystems?
You need a logical volume.  Vgdisplay =96v also gives information on
each lv:
 --- Logical volume ---
  LV Name                /dev/vg_reboot/lvusr
  VG Name                vg_reboot
LV Status              available
LV Size                6.88 GB
  Current LE             220

Creating PV=92s
Create a partition with fdisk of type 8e (Linux LVM) =96 BE CAREFUL not
to change an existing partition.
fdisk /dev/sda will open the fdisk menu for /dev/sda
The letter m prints help information, but you want to use n to create
a new partition.
Accept default for starting location (first available sector).
Default end will be end of disk.
The t option lets you specify type.
Use the letter w once you are sure it=92s right to activate changes.
It will created /dev/sda# for you
Once done, you=92ll need to execute the following command:
		pvcreate /dev/sd# (where # is the partition you just created).
Creating VG=92s and LV=92s
Once you have your pv, creating a volume group is as easy as
executing:
		vgcreate classvg /dev/sda# (where number is the pv you just created)

Once you have your vg, you can create an LV contained within:
lvcreate =96n classlv  -L 1G classvg

NOTE =96 lvcreate and lvextend accept =96L for human readable size as well
as =96l to specify the number of PE=92s
Resizing Filesystems
Resizing filesystems can be done online with resize2fs.
Resize2fs /dev/vg_reboot/lv_to_increase =96 by default it will increase
to LV size
MUCH easier to resize a filesystem in an LV.
LV=92s can be grown without being contiguous.
lvextend =96L +5G /dev/vg_reboot/lv_to_increase will increase the
logical volume by 5G
If you need to resize a partition it can be risky because you need to
reorder your partition scheme.
Command Syntax Basics
Commands consist of three parts:
Binary Name
Options
Arguments

Options are indicated by =93-=94 or =93=97=94 prefixes.
indicates a single letter (Linux Style)
--indicates a word argument (BSD Style)

Arguments take many forms.
Values for options (-L 5G)
Full paths to files or directories on which to perform actions.
=93ls=94 command
Command:  ls
Purpose: Lists files and directories (like dir)
Options: common options are =96la (long listing).  Also use =96t to sort
by time, latest first.  -r reverses the sort.
Common use:  ls -latr
Arguments: directory or path name (fully qualified or in current dir).
=93cat=94 command
Command:  cat
Purpose: display contents of a file
Options: none
Arguments: filename

=93more=94 command
Command:  more
Purpose: another way to show the contents of a file.  Breaks by page,
so you can read it.  Space advances a page, entery advances a line.
Options: none
Arguments: filename

=93grep=94 command
Command:  grep
Purpose: Funny name, serious tool.  Grep looks for pattern matches in
a file.
Options:  =96i is my favorite.  Means case insensitive (remember, UNIX
is case sensitive).  Also grep =96v means show me everyline but the ones
that contain this text.
Arguments: filename


=93cd=94
Command:  cd
Purpose: Changes your current directory.  Default directory is /home/
student.
Options: none
Arguments: Directory name

NOTE:  cd =96 puts you back to your old directory.


=93mkdir=94
Command: mkdir
Purpose: Creates a directory
Options: -p if you=92re making a deep directory mkdir =96p /dir1/dir2/dir3
will create dir1, dir2, and dir3
Arguments: Directory name

=93pwd=94
Command:   pwd
Purpose: Prints your current directory (you are here).
Options: none
Arguments: none

=93rm=94
Command:  rm
Purpose: Removes a file
Options: -f (means don=92t ask me if I=92m sure).  -R means recursive =96
the only way to remove a directory.
Arguments:  file name

NOTE:  rm =96Rf / is ALWAYS a bad idea

=93df=94
Command:  df
Purpose: Displays information on mounted filesystems
Options: -h (human readable.  Calculates in GB, MB, or KB).
Arguments: none

=93cp=94
Command:  cp
Purpose: copies one file or directory to another, preserving the
original.
Options: -R for directories =96p to preserve permissions
Arguments: Directory 1, directory2

=93mv=94
Command: mv
Purpose: Moves one file or a directory to another =96 rename.
Options: none
Arguments: file1, file2

=93echo=94
Command:  echo
Purpose: prints a string to a screen
Options: none we=92ll worry about right now.
Arguments: text --- if spaces, enclose in =93=92s

=93appropos=94
Command: appropos
Purpose: English to geek translator.
Options: none
Arguments: when you know the purpose of the command, appropos might
help you find it.

=93man=94
Command:  man
Purpose: more information than you will ever want to know.
Options: none
Arguments: command

Bash basics
Bash is your friend.  IT is the lazy man=92s shell.
If you know the command name, you can type the first few letters and
hit tab twice.  It will show you your options.
Also, to use your last command (or edit it) just hit up.
Notes
Linux treats spaces as special characters.  Avoid them at all costs.
If you are dead set on using them, you=92ll have to escape them with \.
If you don=92t know how to use a command, try man.
If you want a quick reference, 9 times out of 10 you can type the
command without any options or arguments and hit enter.  It will tell
you.

CMPSC 249:

Introduction to UNIX/Linux
Syllabus Update
Test has been pushed from next week.


All the LVM material from last week=92s class will not be tested on.
Tonight=92s Agenda
Revisit Common Commands

Chain Commands Together

Redirecting Output

Any questions from last week?

Navigating the filesystem
Filesystem:  collection of files and directories contained on a block
device.
Examples of commands to navigate the filesystem:  pwd, mv, cp, ls


Navigating the Filesystem
The best place to start is how to figure out where you are.
To get a listing of your current directory execute:   pwd
Pwd tells you where you are, and as such where your various file
operations will look for their input
The output of that command will look like:
/home/student

Looking for files
We=92ll talk about ls again in a few minutes, but in the meantime,
without any arguments or options, it serves one purpose:
To show you a list of the files in your current directory:
[root@bob ~]# ls
backup      other_stuff    scripty   tmp.sh
French.zip  questions.out  test.txt  uniq_q_n_a.txt
[root@bob ~]#

/ -- ain=92t it cool
/ is where all files start from
To get a listing of all objects in / execute the following:  ls /
Note, in the command above, / serves the purpose of an argument.
The output should look something like:
[root@bob ~]# ls /
backup  boot  etc   lib         media  mnt  Old  proc  sbin     srv
tmp  var
bin     dev   home  lost+found  misc   net  opt  root  selinux  sys
usr



Looking at other directories
What happens when you want to view a filesystem that has thousands of
files in it?
ls will display it=92s output and it will scroll way past the top of
your screen, and you won=92t be able to see it all.
Try it --- go ahead, I=92ll wait  (ls /etc)
This is where you get to meet a UNIX Admin=92s best friend:  |

| -- also cool
| (called =93pipe=94) serves the purpose of taking the output from one
command and passing it as input to another.  It=92s basically a chain.
By itself ls | would do nothing.  However, if we introduce the more
command, our output is broken up by our screen size.
ls |more =96 try it.  I=92ll wait
You can use the Enter key to advance one line at a time, or the space
key basically does a page down, q will exit more without looking at
all the output.
Directories Gone Wild
So, this whole / thing is pretty cool, but what if I want to make my
own directory?
Easy, use mkdir
mkdir takes one argument =96 the destination directory.
If you do not specify a full path (mkdir /home/student/cookiemonster),
mkdir will create the directory in your current directory.
mkdir tmp will create a dir called tmp wherever you are.
Go ahead, try it=85I=92ll wait *use ls to validate*
Moving between directories
So, you know what your pwd is, and you know you want to get to /, but
how do you make / your current directory?
Use cd.  Much like in windows/dos, cd changes your current directory.
If you fully path the directory (cd /home/etc/sysconfig/) you will be
dropped in /etc/sysconfig.
Without specifying a full path (cd cookiemonster) cd will look in your
pwd for that directory and fail if it does not exist.
Go ahead, try it.  I=92ll wait.
cd with no arguments
What happens if you run cd with no arguments?  Where do you get
placed?

Anyone?  Try it and see.
More more
As with most commands in UNIX, more can be used in a few different
ways.
When we used more before, we piped the output of ls to more.
But what if I want to look at a file to see what is in it?
Well, you can use more in one of two ways:  more /etc/termcap
Or, you can use cat to print the contents of the file and pipe it to
more:  cat /etc/termcap | more
What=92s the difference?
Looking only at parts of a file
Look at the beginning of a file:  head /etc/termcap
Look at the end of a file:  tail /etc/termcap.
These commands will show you the first ten and the last ten lines of
the file.
Or, as above, cat /etc/termcap |head and cat /etc/termcap | tail
See a pattern developing?

I wanna see more!!!
Well, head and tail both support one option:  -n
-n specifies a number of lines to see.
tail =96n 20 /etc/termcap will show the last 20 lines.
Try this:  tail =96n 100 /etc/termcap
What do you need to do to make that all visible? tail =96n 100 /etc/
termcap/more

Tail continued
Tail supports an option to view a file in real time:  tail =96f /etc/
termcap.
Will show you the last 10 lines and then sit there.
If any new characters get added to the file =96f forces tail to show
them to you as they arrive.
VERY useful for debugging and monitoring log files.
How do you interrupt it?  Any ideas?
Bueller?
cp/mv
We used cp/mv in lab last week.  Anyone remember how they worked?
cp was to copy, mv was to rename.  Only, mv is actually a move
command, and does more than just rename.
Using cp to copy a file involves two arguments:  source and
destination.
If destination is a directory, cp and mv will put their output in the
directory as opposed to pwd.

Notes
Remember, there is a difference between fully pathing (/etc/
sysconfig/) and shortening the path (sysconfig).
Anyone want to tell us what that difference is?
Cp supports many source files.  You can do something like this:  cp
file1 file2 file3 file4 backup_directory.  All files will be put in
the directory: backup_directory.
Time to remove
rm =3D delete a file
rm =96i puts rm into interactive (windows) mode.  It asks for
confirmation before deleting.  It=92s safer to run as root.
rm accepts many arguments as files to remove.
Let=92s try an experement=85
touch file_1
rm file_1


What happened?  Did it ask you to remove the file, or did it just do
it?
Confirmation Elimination
What do you do if rm asks you if it=92s ok to remove a file every
time?
You can use rm =96f (f for force).
It=92s probably set up as a command alias for your user.
[root@bob ~]# alias
alias rm=3D'rm -i=91





To get rid of the alias execute:  unalias rm --- but this will only
work for this session.  The next time you log in you=92ll have to change
it.

Removing files with wild cards
 * is a wildcard, meaning it matches any character.
If you have a bunch of files to delete that all have a similar name,
you can use * to your advantage.
Let=92s try:
Create the files:
	touch file_1
	touch file_2
	touch file_3
	touch file_4
Wild cards Continued
We created the files, now let=92s remove them.
To do it manually would require either one long command (rm file_1
file_2 file_3 file_4) or four separate remove commands.
Instead, we can save ourselves some work:
rm file_*
Common error scenarios
Command not found:  indicates you have spelled your base command
wrong.
Using copy instead of cp
No such file or directory:  indicates that one of your options is
incorrect (you=92ve tried to look at a file that doesn=92t exist)
ls /cookiemonster

Errors (2)
If you get an error message, but you are sure that you=92ve spelled the
command right, often times you can use man to figure out what you are
doing wrong.
man ls
Navigating man pages is similar to navigating output from more.

Redirecting Output
We use | to move output from one program to another in a command
string.
What if we wanted our commands to output directories to a file?
There are two ways to do this.  One way appends to an existing file,
the other creates a new file.
Redirecting Output
ls > ls.out =96 this creates a new file called ls.out.  If ls.out
already existed, it would destroy the file and create a new one for
us.
ls >> ls.out =96 this will append the output of our command to the
existing ls.out file.  If ls.out did not exist, it would create it for
us.
Line counting
Sometimes you really need to see how big a file is.  The wc command
counts certain types of entries.
To see how many lines are in the /etc/termcap file, you=92d use:  cat /
etc/termcap | wc =96l
wc =96w shows how many words
wc =96c shows how many characters
Without any options, wc will show you all three:
[root@bob ~]# cat /etc/termcap |wc
  19092   91266  807103
[root@bob ~]#
                                    Lines   Chars     Words

Command Arguments
As we discussed last week, commands are made up of three pieces:
Binary
Options (Flags =96 preceeded with a -)
Arguments
These arguments can be combined in various ways.

Ls Options
ls =96l shows us more columns of output.
[root@bob ~]# ls
backup      other_stuff    scripty   tmp.sh
French.zip  questions.out  test.txt  uniq_q_n_a.txt


[root@bob ~]# ls -l
total 1524
drwxr-xr-x 4 root root    4096 Dec 23  2006 backup

Permissions  Owner Group Size Time Name

Ls Options
Using ls =96la will show you hidden files as well.
Hidden files begin with a .
Other than that, the output is the same to ls =96l
Using the =96t option for ls sorts the files by modification time with
the latest first.
Using the =96r option combined with =96t reverses the time search order,
and puts oldest last.
Combining ls Options
So, we like =96l, -a, -t, and =96r for ls.  It gives as much information
as we=92d need to look at the files.  How do we use them?
ls =96l =96a =96t =96r  (long way)
ls =96latr (lazy way)
The options are able to be combined by a single: 			=96

This is true for most commands you will use.
Sorting your output
By default the output you will from some commands seems to have no
real order.
 Not all files are maintained in alphabetical order.
So, the powers that be developed a command to help us poor humans:
sort
Sorting 2
The /etc/passwd file contains information on all users on the
system.
When new users get created, they get added to the bottom of the
file.
It gets out of hand quickly.  So, let=92s try the following:
cat /etc/passwd =96 It=92s hard to find entries
sort /etc/passwd =96 much easier to read
More sorting
Looking to reverse that sort, backwards alphabetical anyone?
sort =96r has got your back.
Very similar to the ls =96latr (reverse time sort)
Just remember, UNIX is case sensitive, so A does not equal a out of
the box.
You can use sort =96f to ignore case


If you have a list of files that has multiple entries, many of which
are the same, you can use sort to extract unique records:     sort =96u
We all need a break
Great time to break.  Be back here in 10 minutes.
The sleep command
Sometimes you are writing a script that needs to allow time for
something to complete.
For that the sleep command was invented.
sleep takes one argument, and one argument only.  A number.
It=92s job is basically to wait that many seconds and the return control
to you.  sleep 5 sleeps for 5 seconds, etc.
Passing Arguments
You can see what=92s happening with arguments by issuing this command:
echo A B C D > file
cat file


What does this tell us?
echo is spawned with 4 arguments
echo operates and redirects its output to a file
Combining files
Suppose you have three separate files that you need in one big file.
No problem!
date >file1
echo hello world > file2
ls > file3
Cat each of these files individually to see the results.
Merge them by executing:
cat file1 file2 file3 > bigfile
cat bigfile
Locating Specific lines in a file
grep is hands down one of the most useful utilities ever.
Quickly described, grep simply looks for a pattern and outputs the
match.
A quick example would be:
grep student /etc/passwd
What else can grep do?
You can use grep to find files:
	ls |grep =93file1=94
You can use grep to match case insensitive:
			grep =96i student /etc/passwd
You can use grep to match everything but:
grep =96v student /etc/passwd
Notes
Just a reminder, many utilities can be executed as part of a command
string:
cat /etc/passwd |grep =96i student
They can also be executed independently
grep =96i student /etc/passwd




Both methods produce identical output
Some utilities are dumb
cat, more, sort when executed without any arguments or options will
just sit there and stare at you blankly
Why?  Because they are waiting for you to do something.
Execute the sort command and hit enter.
What happens?
Sort with nothing
You didn=92t give it a file to work with.  You didn=92t give it a stream
to work with, so it=92s waiting for you to provide the data for it to do
it=92s work.
Enter the following strings:
Hello
Goodbye
42
AAA
Aaa
Then hold ctrl and hit D.  This tells sort that it=92s reached the end
of the input and it does its work.  It will use your input as its
source.
Using cat to create a new file
cat > newfile
Opens the cat binary and attaches to newfile for output.
Drops to the input method we just used to get it=92s contents.  Enter:
Hello from cat
Then ctrl-D.
cat newfile =96 will show your entry.
You can also create a file with echo:  echo =93hello=94 > newfile2

CMPSC 249:

Introduction to UNIX/Linux
Week 4 -- vi

Announcements

Test next week
We will review at the end of lecture


vi
The vi that we are using tonight is not actually, it=92s vim (VI
iMproved).
VIM is not the same as vi, but the basics are close.  Not all UNIXes
are the same when it comes to vi.
Type the following command:  vi
~                              VIM - Vi IMproved
~
~                               version 7.0.109
~                           by Bram Moolenaar et al.
~                 Vim is open source and freely distributable


What now?
~                type  :q<Enter>               to exit
~                type  :help<Enter>  or  <F1>  for on-line help
~                type  :help version7<Enter>   for version info
This information is useful, because it gives you some of vi=92s more
basic commands.
Use :q to exit vi.

VI modes
VI has two basic modes:  command and insert.
VI always starts in command mode.
Special mode for vi control commands.
Insert mode is the only way to actually modify text.
Insert mode
VI help
So, when you enter vi, you can use :help to navigate through the help
pages.
It=92s a little quirky, and easy to get lost.  I often refer to:
http://vimdoc.sourceforge.net/htmldoc/help.html
What=92s vi for?
As we=92ve discussed, the vast majority of UNIX programs are controlled
by text files.
VI gives you a method to edit those files.  VI can:
Move around a file
Delete Text
Copy and Paste Text
Moving around (viewing) a file
The arrow keys can help you move through a file.  For example, execute
the following command:  vi /etc/passwd
Use the arrow keys to scroll up, down, left, and right in the file.

Quitting vi
Ctrl-c will not work with vi.
You can manually kill the process from another window or use the q
command.
Esc + :q to exit (might not need esc, but always good to be safe)
You must ALWAYS precede commands with :
Moving 2
In vi, there are special key sequences to perform certain tasks.
For example:
Shift + G moves to the last line in a file
$ moves to the end of the line you are currently on.
: and a number moves to that specific line (:1 moves to line 1)

Who needs a mouse?
When not in insert mode, vi allows you to move around with more than
just arrow keys.
w allows you to move your cursor from word to word.
e moves the cursor to the end of the word
b moves back one word.
Cursor positioning is key to hitting insert mode running.


Searching in a file
You can use vi to search for a specific pattern in a file.
Anyone remember the command we used to search for patterns last week?
In vi you precede your search string with a /
vi /etc/passwd
Type:     /root    it will take you to the line that matches root.
The =93n=94 key will move to the next match.
An uppercase N will take you to the previous match.
Searching continued
UNIX is case sensitive, remember?
Grep, sort, and other utilities have builtin ways of being case-
agnostic.
Vi is no different, although there is no special command =96 it=92s a
setting.
You need to use the following:
Esc + :set ignorecase
Using VI to edit an existing file
Find one of the files we created last week in lab.
vi that file (vi $filename)
Go to the end of the file.
Go to the end of the line.
Append the following line:  ABC123
Save the file (esc + :wq)
cat it to ensure the text got saved.
Using vi to create a new file
Similar to some of the topics we covered last week, if you give vi an
argument that is a filename, vi will open that file.
If the filename does not exist, vi will create it for you.
Let=92s execute the following command:
			vi vi_file_create.txt


Switching out of command mode
So, you=92ve opened your file, and you want to put text in it.
If this is truly a new file, vi will tell you at the bottom:
"vi_tmp_file.txt" [New File]

But, you=92re in command mode.
Type the letter h.  Nothing happens.

To get out of insert mode, type:  i

I is a vi command that switches to insert mode.  Now, you can type
till your heart=92s content.  Go ahead, put a few lines of text in.

Done entering text?
If you hit :q here, all changes are lost.  Your file will not
created.
So, how you actually write to your file?
Four key components:
Hit the escape key.  This is the way to exit command mode
:  -- Indicates a command string is coming
w =96 is the vi command to write your changes to the file.
q =96 command to quit.



Often the command sequence used is:  Esc + :wq
Accomplishes this all in one command
Checking your input
cat vi_tmp_file.txt
See your text?
You=92ve now used vi to create a file.

What commands did you use to create files last week?
Key Concept
=93vi rocks=94 =96 Ron Utsinger, Caterpillar, Inc UNIX Operations.
The Esc key switches from insert mode to command mode.
If you accidentally put your command in your text, you need to switch
to command mode.
Before you execute a command it is a good idea to ensure you=92re out of
insert mode by using escape.
Functions
You=92ve probably noticed some commands are not preceded by a :
These are hotkeys, or macros.  I call them functions.
There are functions to perform various tasks.
Most of these functions, when preceded with a number will perform that
function that number of times.  20dd will delete 20 lines, etc.




These functions cannot be performed in insert mode.  So, if you are in
insert mode you=92ll need to hit escape first.
Deleting Lines
dd is the function to delete the current line.
If you precede dd with a number it will remove that many lines.  From
your cursor down.
Let=92s create a file.
vi tmp_file1
20i aaaa (enter)
Esc + :w
Now, let=92s delete 1 line
Dd
Now, let=92s delete 10 lines
10dd    esc + :wq
cat the file, and count the lines.  How many are there?
Deleting a specific line
Knowing the line number can be advantageous.  You can delete a line
based on it=92s number.
For example: to delete line 5, execute:
:5d
Deleting Characters
You can delete characters with the delete key and backspace keys when
insert mode.
In command mode, there is an alternative:  x
Why?  Sometimes you just don=92t want to go to insert mode.
vi tmp_file1 again.  Delete the remaining lines (9dd)
Go to insert mode and enter:  abcd
Hit escape, and move your cursor to c
Hit x


Move your cursor back to b, and hit 2x.  What happened?
Deleting a word
Much line x can delete a character , you can delete a word by
highlighting it and executing:
dw
Undo
Yes, we realize that people make mistakes.
u executes the undo command.  It will undo your previous text add or
deletion.
Hit u once =96 what happened?
Hit it again =96 what happened?
Changing a word
Vi gives you the option to change an entire word without actually
going into insert mode first.
You simply highlight any letter in the word, and enter:
cw
The existing word is replaced, and you are allowed to insert a new one
in its place.

Changing a letter
VI also gives you the option to change just a letter without going
into insert mode first.
You simply move your cursor to the word you want to replace and
enter:
cl
The existing letter is removed and you are allowed to insert a new one
in its place.

Yanking (copying)
VI supports functionality similar to that of copy and paste.
To copy an entire line, you type:
yy (yank)
To copy a word, you type:
yw (Yank Word)
To copy a letter, you type:
yl (Yank Letter)
As with all functions, you can precede any of the y=92s above with a
number to yank that many lines/words/letters
Pasting
Pasting is accomplished via the following function:
p
Regardless if you have yanked a word, letter, or line p will paste
what is in the buffer.
You can precede p with a number to paste the line that many times.


A line will be pasted below your current line

A word or letter will be pasted after your current cursor position.

An example
vi paste_test
i for insert mode
Enter the following text:
abcd
1234
Move your cursor to the first line and type:
	yy
	then p
You should now have two lines of abcd.



Example 2
Delete the second abcd line with dd
Move back to the first line, and type yy.
Move your arrow key down to the second line and hit p.
Your file should now look like:
abcd
	1234
	abcd
You can move your cursor between yanks and pastes.
Example 3
Delete the second abcd line with dd.
Move back to the first line and type 2yy (yank 2 lines).
Then hit p.  Your file will now look like:
		abcd
		abcd
		1234
		1234
Why?  Vi pastes lines below your current cursor position.
Hit u, then move down to the bottom of the file and type p, does that
look better?
Example 4
Delete the extra lines, and move back to the top line.
Enter yy
Move to the bottom of the file and type 20p.
You should now have abcd, 1234, and then 20 more abcd=92s
Creating a new line
We can use Shift G and $ to go the the last line and the end of that
line respectively.  From there we can hit enter and put a new line
below the last.
Is there a better way?  Yes, when you are on a line and you want to
start a new line directly below, you can use the o key to insert a new
line and begin typing.  o will automatically put you into insert
mode.
A Capital O will create a new line above the cursor.
Also, capital A will automatically create a new line at the bottom of
the file and put you in insert mode.
Mistakes
So, what if you horribly mess up the file in the process of miskeying
functions?
Easy, all you have to do is quit without saving:
Esc + :q
What happened?  Why won=92t it let you leave?



Esc + :q!    (! Means force)
Reading in another file
So, you=92ve opened vi, but you forgot to make a copy of your original
file before editing.
Sure, you COULD leave vi, copy it and open up vi again.
But there are better ways.

Reading in another file =96 Way 1
Way 1 is slightly dangerous in that you actually edit the live file.
You could accidentally overwrite the live file.
This violates Creighton=92s rule #1:  Always make a backup before you
change something.
So, assume you vi /etc/passwd, and you make changes.  But you don=92t
want your changes to go live yet.  Easy:
Esc + :w filename will write to a new file
Reading in another file =96 Way 2
Method 2 involves telling vi to input the contents of another file
with read.
Let=92s try this:
vi passwd_copy
Esc + :r /etc/passwd
Esc + :wq
Cat the file =96 what just happened?


You copied the contents of /etc/passwd into your file and saved it as
passwd_copy
VI=92ing a directory
This is my favorite feature of vim.  Why?  Because I=92m lazy.
In vim, you can call vi with the argument of a directory.  It will
give you a list of files in that directory, and let you pick a file.
Arrow keys and enter select.
Then, you are editing that file.
Try it, type vi /etc/
What happens?
More navigation
Now that we know the power that numbers hold in front of functions,
get out of insert mode.
Type 15, and then the down key.
You=92ve just moved 15 lines down.
See why lazy admins like vi?
View
View is a utility that is bundled with vi.
We used more, head, and tail last week to look at big files.
View gives us another method to do that.
It is basically a read-only version of vi.
You can search, use Shift G, or $, /, etc to navigate through bigger
files.
More tricks
$ moves to the end of a line
:$ moves to the last line of the file (like Shift G)
^ moves to the beginning of the line you=92re on.
w advances a word from the beginning of the word (try 3w)
b moves back one word (try 3b)
A number followed by | moves to that position in the line.
E moves word to word by the end of the word (5e)
Tricks continued
L moves the cursor to the lowest line on the screen
M moves the cursor to the middle line on the screen
H moves the cursor to the first line on the screen.
Screen Scrolling
Ctrl-D moves down one-half screen at a time
Ctrl-U moves up one half screen at a time
Ctrl-F moves down one whole screen
Ctrl-B moves up one whole screen




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?02a63bf9-fa84-4dba-a5c9-94053332584f>