Saturday, September 19, 2009

mysql -u root
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.0.45 Source distribution

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> create database dbname;
Query OK, 1 row affected (0.01 sec)


mysql> grant all privileges on dbname.* to 'dbname'@'localhost';
Query OK, 0 rows affected (0.00 sec)


mysql> grant all privileges on dbname.* to 'dbname'@'%';
Query OK, 0 rows affected (0.00 sec)

Friday, September 18, 2009

Disk space usage using df command.

To get a listing of free space on all mounted filesystems execute df command with no arguments.

# df
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/mapper/VolGroup00-LogVol00 33423168 16560892 15137044 53% /
/dev/sda1 101086 14952 80915 16% /boot
tmpfs 257560 0 257560 0% /dev/shm


Use the df command with -h option to displays the space in human-readable units , the example below show the freespace available in Mb unit:

# df -h
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/VolGroup00-LogVol00 32G 16G 15G 53% /
/dev/sda1 99M 15M 80M 16% /boot
tmpfs 252M 0 252M 0% /dev/shm


Note: The Use% column shows what percentage of the filesystem that currently in use.

To show space on the filesystems those directories are mounted on:

# df /boot
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/sda1 101086 14952 80915 16% /boot


The df command can be use to get information on inode usage on all mounted filesystem.  To show the inode information execute df command with the ( -i  ) option:

df -i
Filesystem Inodes IUsed IFree IUse% Mounted on
/dev/mapper/VolGroup00-LogVol00 8633856 313455 8320401 4% /
/dev/sda1 26104 37 26067 1% /boot
tmpfs 64390 1 64389 1% /dev/shm


The following are some of the flags and arguments that can be used for the df command:
-a, --all include filesystems having 0 blocks
-B, --block-size=SIZE use SIZE-byte blocks
-h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)
-H, --si likewise, but use powers of 1000 not 1024
-i, --inodes list inode information instead of block usage
-k like --block-size=1K
-l, --local limit listing to local filesystems
--no-sync do not invoke sync before getting usage info (default)
-P, --portability use the POSIX output format
--sync invoke sync before getting usage info
-t, --type=TYPE limit listing to filesystems of type TYPE
-T, --print-type print filesystem type
-x, --exclude-type=TYPE limit listing to filesystems not of type TYPE
-v (ignored)
--help display this help and exit
--version output version information and exit

NAME:
df - report filesystem disk space usage
Usage: df [OPTION]... [FILE]...

for more information on df command:
# info df
# man df
# df --help

Display the size of file and directory in Linux

[root@fedora ~]# du -h
4.0K ./.rhopenoffice1.1/program/addin
108K ./.gnome2
28K ./.nautilus/metafiles
32K ./.nautilus
6.0M ./.mozilla/firefox/1wvl2gwo.default/Cache
12K ./.mozilla/firefox/1wvl2gwo.default/chrome
12M .
 
The output from above command show the size of each file, directory and with the total size used in your system in human readable size ( -h ).
 

Get the total size of current directory.

 
   The du command can be use to determine the total size of file in current directory.  The example below show the du command use with -s (summarize) and -h (human readable format) option to summaries the size of disk space taken by current directory.
 
[root@fedora ~]# du -s
768096 .
[root@fedora ~]# du -sh
751M .
[root@fedora ~]#
 
To get the size of file and directory in current directory.
 
[root@fedora ~]# du -sh *
14M 20060524-033-x86.exe
85M labu-punyer
8.0K libjmti.odt
4.0K linux-feeds.txt
4.0K mambo_conf.txt
8.0K yumex-0-1.0.1-1.0.fc5.html
408K yumex-1.0.1-1.0.fc5.noarch.rpm
8.0K yum install
11M zope-2.8.5-1.fc5.i386.rpm
[root@fedora ~]#
 

Display the size of specific file extension.

 
   The example below show du command execute with -c option to get the size of each file that have filename ending with .txt and then display grand total of all files in human readable format.
 
[root@fedora ~]# du -ch *.txt
4.0K create.drupal-2.txt
4.0K create.drupal.db.txt
4.0K drupal-pass.txt
4.0K joomla-bazz.txt
4.0K linux-feeds.txt
4.0K mambo_conf.txt
8.0K msql-bazz.txt
4.0K setup_mysql_mambo.txt
4.0K simple.txt
40K total
[root@fedora ~]#
 

Check the size of home directory.

 
   The example below show the use of du command to get the disk usage of each user home directory on the system.
 
[root@fedora home]# pwd
/home
[root@fedora home]# du -sh *
492K bazz
48K botol
44K hamirul
22M kambing
48K kayu
56K labu
80K sysuser
40K william
40K ycluckers
[root@fedora home]#
 
To produce grand total of the /home directory size.
 
[root@fedora home]# pwd
/home
[root@fedora home]# du -csh *
492K bazz
48K botol
44K hamirul
22M kambing
48K kayu
56K labu
80K sysuser
40K william
40K ycluckers
23M total
[root@fedora home]#
 
The following are some of the flags and arguments that can be used for the du command:
 
· -a, --all         write counts for all files, not just directories
· --apparent-size         print apparent sizes, rather than disk usage; although the apparent size is usually smaller, it may be larger due to holes in (`sparse') files, internal fragmentation, indirect blocks, and the like
· -B, --block-size=SIZE         use SIZE-byte blocks
· -b, --bytes         equivalent to `--apparent-size --block-size=1'
· -c, --total         produce a grand total
· -D, --dereference-args         dereference FILEs that are symbolic links
· -H like --si, but also evokes a warning; will soon change to be equivalent to --dereference-args (-D)
· -h, --human-readable         print sizes in human readable format (e.g., 1K 234M 2G)
· --si like -h, but use powers of 1000 not 1024
· -k like --block-size=1K
· -l, --count-links count sizes many times if hard linked
· -L, --dereference dereference all symbolic links
· -P, --no-dereference don't follow any symbolic links (this is the default)
· -0, --null end each output line with 0 byte rather than newline
· -S, --separate-dirs do not include size of subdirectories
· -s, --summarize display only a total for each argument
· -x, --one-file-system skip directories on different filesystems
· -X FILE, --exclude-from=FILE Exclude files that match any pattern in FILE.
· --exclude=PATTERN Exclude files that match PATTERN.
· --max-depth=N print the total for a directory (or file, with --all) only if it is N or fewer levels below the command line argument; --max-depth=0 is the same as --summarize
· --help display this help and exit
· --version output version information and exit
 
NAME
du - estimate file space usage
 Usage: du [OPTION]... [FILE]...
Summarize disk usage of each FILE, recursively for directories.
 
More information on du command:
# info du
# man du
# du --help

Cancel Shutdown on Fedora Linux using shutdown Command

Running Shutdown Process on Background


1.  Running shutdown process on background... The shutdown command bellow tell Fedora system to shutdown at 8:00 pm (20:00).
Cancel Shutdown on Fedora Linux using shutdown command, Running shutdown process on background
[root@fedora ~]# shutdown -h 20:00 "shutdown in progress" &
[1] 3143
[root@fedora ~]#
Broadcast message from root@fedora.linux.com
        (/dev/pts/1) at 4:11 ...

The system is going down for halt in 949 minutes!
shutdown in progress

[root@fedora ~]#

Cancel Shutdown


2.  To cancel shutdown that in progress on Fedora system, execute shutdown -c as show on example below
To cancel shutdown that in progress on Fedora system
[root@fedora ~]# shutdown -c "cancel shutdown"

Broadcast message from root@fedora.linux.com
        (/dev/pts/0) at 4:28 ...

cancel shutdown
[root@fedora ~]#

Shutdown error:


1.  If you get the "-bash: shutdown: command not found" error when execute shutdown command as show on example below...
Shutdown:
[fedora@fedora ~]$ shutdown -h 20:00 "shutdown in progress"
-bash: shutdown: command not found
[fedora@fedora ~]$

Cancel Shutdown:
[fedora@fedora ~]$ shutdown -c "cancel shutdown"
-bash: shutdown: command not found
[fedora@fedora ~]$

Shutdown error solutions:


 2.  you may need to log in as root user to execute shutdown command....or use the su command as show on example below and supply the root user password when ask...

Shutdown:
[fedora@fedora ~]$ su - -c "shutdown -h 20:00 'shutdown in progress'&"
Password:
[fedora@fedora ~]$
Broadcast message from root@fedora.linux.com
        (unknown) at 4:42 ...

The system is going down for halt in 918 minutes!
shutdown in progress

[fedora@fedora ~]$

Cancel Shutdown:
[fedora@fedora ~]$ su - -c "shutdown -c 'cancel shutdown'"
Password:
shutdown: Shutdown cancelled

Broadcast message from root@fedora.linux.com
        (/dev/pts/1) at 4:41 ...

cancel shutdown
[fedora@fedora ~]$

Note: This canceling shutdown command above have been tested on Fedora 7, Fedora 8, Fedora 9, Fedora 10

check Linux Version and System Information

Get and display all system information on Linux machine:
Dispaly Linux system information uname -a
[root@fedora ~]# uname -a
Linux fedora.linux.com 2.6.25-14.fc9.i686 #1 SMP Thu May 1 06:28:41 EDT 2008 i686 i686 i386 GNU/Linux
[root@fedora ~]#

Get and display the Linux kernel name:
Dispaly Linux kernel name uname
[root@fedora ~]# uname
Linux
[root@fedora ~]#

or
[root@fedora ~]# uname -s
Linux
[root@fedora ~]#

Get and display Linux hostname or node name:
Display Linux Hostname uname
[root@fedora ~]# uname -n
fedora.linux.com
[root@fedora ~]#

Get and display Linux kernel release or could be use to check kernel version name :
Display Linux kernel release
[root@fedora ~]# uname -r
2.6.25-14.fc9.i686
[root@fedora ~]#

Get and display Linux kernel version:
Display Linux kernel version
[root@fedora ~]# uname -v 
#1 SMP Thu May 1 06:28:41 EDT 2008
[root@fedora ~]#

Get and display Linux machine hardware name:
Display Linux hardware name
[root@fedora ~]# uname -m
i686
[root@fedora ~]#

Get and display Linux processor name:
Display Linux processor name
[root@fedora ~]# uname -p
i686
[root@fedora ~]#

Get and display Linux hardware platform:
Display Linux Hardware Platform name
[root@fedora ~]# uname -i
i386
[root@fedora ~]#

Get and display Linux operating system name:
Display Linux Operating System with uname
[root@fedora ~]# uname -o
GNU/Linux

Thursday, September 17, 2009

Adding a port to firewall

iptables -A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 5432 -j ACCEPT

To Delete the Virtual Box :

VBoxDeleteIF vbox0
VBoxDeleteIF vbox1

To List the Bridge connection in Linux

brctl show

Down the bridge connection

ifconfig br0 down

To list the networkconfiguration

cmd : ifconfig

Edit the DNS Configuration for linux

vi /etc/resolv.conf

To make Ethernet configuration up

ifconfig eth0 up (Or) ifup eth0

Adding subnet mask ,default gateway

route add -net 10.10.16.0 netmask 255.255.240.0 eth0

Adding bridge connection

VBoxAddIF vbox0 root br0

To remove the default gateway

route del default gw
route add default gw


To list the port

netstat -tulpn | less

To check the process runnning on linux

ps -aux

JAVA PATH Setup in Linux

Edit vi /etc/profile

export ANT_HOME=/opt/sfw/apache-ant-1.7.0
export JAVA_HOME=/opt/sfw/jdk1.6.0_06
export PATH=$JAVA_HOME/bin:$PATH
export PATH=$ANT_HOME/bin:$PATH
export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
export JAVA_HOME PATH

Burn ISO image to DVD

cdrecord -v -sao dev=/dev/hda UDF_Volume.iso

Steps to install memcache


1)# which phpize

2)If the result is usr/bin/phpize then run the command

#export PATH=/opt/lampp/bin:$PATH.

3)Install memcached using

#apt-get install memcached.

4)Download memcache client using the command

#wget http://pecl.php.net/package/memcache/memcache-2.2.5.tar.gz

5)Extract the downloaded package using the command

#tar -xzf memcache-2.2.5.tar.tz

6)# cd memcache-2.2.5

7)# /opt/lampp/bin/phpize

8)# ./configure -enable-memcache -with-php-config=/opt/lampp/bin/php-config-5.1.6(your php version)

9)If u get “c compiler cannot create executable files” then u need to run

#apt-get install build-essential

10)If u get Zlib-dir not found then u need to execute

#./configure -enable-memcache –with zlib-dir=/opt/lampp –with-php-config=/opt/lampp/bin/php-config-5.1.6(your php version)

11)# make

12)# make install

13)open php.ini and search for extension and add

extension=” memcache.so”

and

when we execute make install it will give you the extensions folder path copy that and add it in php.in.

For example:

when we execute make install command the path displays like

“/opt/lampp/lib/php/extensions/no-debug-non-zts-20050922” and now we need to add the below statement to php.ini

“extension-dir=/opt/lampp/lib/php/extensions/no-debug-non-zts-20050922 to php.ini”

14)Restart your server

15)Open browser and give http://localhost/xampp/phpinfo

search for memcache in browser you will find it else again run the complete steps again.

Setting up public key authentication over SSH

applelinuxmisc

Every time I want to setup public key authentication over SSH, I have to look it up, and I've never found a simple guide, so here's mine.

Generate key on local machine

ssh-keygen -t rsa

It will ask you for a password but you can leave it blank.

Note you could also pick -t dsa if you prefer.

Ensure that the remote server has a .ssh directory

Make sure the server your connecting to has a .ssh directory in your home directory. If it doesn't exist you can run the ssh-keygen command above, and it will create one with the correct permissions.

Copy your local public key to the remote server

If your remote server doesn't have a file called ~/.ssh/authorized_keys2 then we can create it. If that file already exists, you need to append to it instead of overwriting it, which the command below would do:

scp ~/.ssh/id_rsa.pub remote.server.com:.ssh/authorized_keys2

Now ssh to the remote server

Now you can ssh to the remote server without entering your password.

Security

Now keep in mind that all someone needs to login to the remote server, is the file on your local machine ~/.ssh/id_rsa, so make sure it is secure.

Creating users in Win XP through command prompt

We all know how to create a new user account in Windows XP .

Just go to Start and click on Control panel. Now open the "user account tool".

Here you will be seeing an option Like "create an account".
Well enter any windows XP user and click on create account.
This is how you will be creating a new Windows XP user.

But there is a different procedure to create a new Windows Xp user using dos prompt.

To create a new account you have to type as follows :
net user USERNAME PASSWORD \ADD

To delete the account type as follows :
net user USERNAME \del

To get admin rights type as follows :
net localgroup administrators username \add

The complete command is
[username [password | *] [options]] [/DOMAIN]
username {password | *} /ADD [options] [/DOMAIN]
username [/DELETE] [/DOMAIN]

DB Dumps

MySql Dump

mysqldump --protocol tcp -P portnumber -h localhost -u root databasename > filename.sql

DB dump of all database

shell> mysqldump --all-databases > all_databases.sql

Postgresql dump

To get the database dump execute the below commands from outside the database

1. /usr/bin/pg_dump -U postgres -f - only for structure;
2. /usr/bin/pg_dump -U -d > - data + structure;

3.pg_dump dbname -U username -h hostname -p > filename.sql

4.pg_dumpall -U username -h hostname -p > filename.sql

Mysql Commands

To list the users,host in the mysql

select Host ,User ,Password from mysql.user;

To set mysql root password

mysqladmin -u root password newpassword ;


To delete the host from mysql

DELETE FROM mysql.user where host=hostname;


To drop the user

DROP USER 'desiyou'@'localhost';


To Start the multiple instance in Mysql


mysqld_multi --config-file=/etc/my2.cnf start 1
mysqld_multi --config-file=/etc/my2.cnf start 2


Mysql Case Sensitive

vim /etc/my.cnf

lower_case_table_names=1

To know the status of mysql :

SHOW STATUS;

To know the mysql process status :

SHOW FULL PROCESSLIST\G
show variables;

Running multiple Databases Servers on linux

Running multiple Databases Servers:
======================================

do the following as root.

1. create directories:

mkdir /var/lib/mysql1
mkdir /var/lib/mysql2

2. change the user and group

chown mysql /var/lib/mysql1
chgrp mysql /var/lib/mysql1
chown mysql /var/lib/mysql2
chgrp mysql /var/lib/mysql2

3. copy my2.cnf to /etc

4. execute the following:

mysql_install_db --user=mysql --datadir=/var/lib/mysql1 --verbose
mysql_install_db --user=mysql --datadir=/var/lib/mysql2 --verbose

5. start databases.

mysqld_multi --config-file=/etc/my2.cnf start 1
mysqld_multi --config-file=/etc/my2.cnf start 2

---

the port for database 1 is 3406
the port for database 2 is 3506.



vim /etc/my2.cnf


[mysqld1]
port=3406
datadir=/var/lib/mysql1
socket=/var/lib/mysql1/mysql.sock
user=mysql
# Default to using old password format for compatibility with mysql 3.x
# clients (those using the mysqlclient10 compatibility package).
old_passwords=1
innodb_data_home_dir = /var/lib/mysql1/
innodb_data_file_path = ibdata1:10M:autoextend
innodb_log_group_home_dir = /var/lib/mysql1/
innodb_log_arch_dir = /var/lib/mysql1/
innodb_buffer_pool_size = 16M
innodb_additional_mem_pool_size = 2M
innodb_log_file_size = 5M
innodb_log_buffer_size = 8M
innodb_flush_log_at_trx_commit = 1
innodb_lock_wait_timeout = 50

[mysqld2]
port=3506
datadir=/var/lib/mysql2
socket=/var/lib/mysql2/mysql.sock
user=mysql
# Default to using old password format for compatibility with mysql 3.x
# clients (those using the mysqlclient10 compatibility package).
old_passwords=1
innodb_data_home_dir = /var/lib/mysql2/
innodb_data_file_path = ibdata1:10M:autoextend
innodb_log_group_home_dir = /var/lib/mysql2/
innodb_log_arch_dir = /var/lib/mysql2/
innodb_buffer_pool_size = 16M
innodb_additional_mem_pool_size = 2M
innodb_log_file_size = 5M
innodb_log_buffer_size = 8M
innodb_flush_log_at_trx_commit = 1
innodb_lock_wait_timeout = 50

[mysqld_safe]
log-error=/var/log/mysqld2.log
pid-file=/var/run/mysqld2/mysqld2.pid

Install Virtualbox in Centos and configure Bridge network

Install Virtualbox in Centos and configure Bridge network


After Install Virtual OS in Master Machine do the below steps


Step 1: login to the master OS and open terminal.

Step 2: Go to /etc/sysconfig/network-scripts/

Step 3: Install bridge-utils by using the below command.

#Yum install bridge-utils

#mkdir backup

#cp ifcfg-eth0 backup/

#vi ifcfg-eth0

Step 4: comment IPADDR

Step 5: create ifcfg-br0 file and add the below comments in ifcfg-br0


DEVICE=br0

BOOTPROTO=none

#HWADDR=00:1c:c0:61:d8:b2

ONBOOT=yes

NETMASK=255.255.240.0

IPADDR=10.10.17.4

GATEWAY=10.10.16.13

TYPE=Bridge

USERCTL=no

IPV6INIT=no

PEERDNS=yes


Step 6: give your IPADDR,NETMASK and GATEWAY and then run the below commands in terminal.


#/usr/sbin/brctl addbr br0
#/usr/sbin/brctl setfd br0 0

#/usr/sbin/brctl sethello br0 0 #?
#/usr/sbin/brctl addif br0 eth0


#/etc/init.d/network restart

#brctl show


Step 7: Open virtualbox and select the virtual OS(slave)

Step 8: click the settings then it shows a new window.

Step 9: In here select network.

Step 10: In Adapter 1 change the Attached to dropdown to Host Interface and give Interface Name vbox0


Step 11: Go to the Master OS terminal and execute the below command

#VboxAddIF vbox0 root br0

Step 12: start the slave machine and set ip and ping some Lan IP if its pinging fine there is no problem.

Step 13: If its not pinging check your master and slave firewall configurations.

Reset mysql root password on Linux

Reset mysql root password on Centos

  1. Stop the MySQL daemon : service mysqld stop
  2. Start MySQL in safe mode with the –skip-grant-tables and -u root options in background : mysqld_safe –skip-grant-tables -u root &
  3. Start the command line client as root : mysql -u root
  4. Issue the MySQL command to reset the root password : UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';
  5. Issue the flush privileges command : FLUSH PRIVILEGES;
  6. Quit the command line tool : quit
  7. Stop the MySQL process : kill `cat /var/run/mysqld/mysqld.pid`
  8. Restart the MySQL daemon : service mysqld start
  9. Log in as root to make sure the new password is active : mysql -u root -p

Here's a screenshot so you can see how it actually goes :

reset-mysql-root-password.jpg



Set / change / reset the MySQL root password on Ubuntu . Enter the following lines in your terminal.
  1. Stop the MySQL Server.
    sudo /etc/init.d/mysql stop

  2. Start the mysqld configuration.
    sudo mysqld --skip-grant-tables &

  3. Login to MySQL as root.
    mysql -u root mysql

  4. Replace YOURNEWPASSWORD with your new password!
    UPDATE user SET Password=PASSWORD('YOURNEWPASSWORD') WHERE User='root'; FLUSH PRIVILEGES; exit;

Note: This method is not regarded as the securest way of resetting the password. However it works.

Enable Clean URLs

Clean URL enabling in Ubuntu.


Step: 1

a2enmod rewrite


Step: 2





RewriteEngine On


Step: 3


To enable mod_rewrite in apache2.2 -specaily for debian.

In default installion of apache2.2 on debian never enable mod_rewrite default. So you may need to enable .

First install the apache2.2 with this command :
debian user please use “su” before start this process
ubuntu user please use “sudo su” before start this process

apt-get install apache2 (it will install apache 2.2)

now use locate to find if the mod_rewrite.so is availble on your server

updatedb
locate mod_rewrite.so

it will found in “/usr/lib/apache2/modules”

new apache follow some folders to enable and desuable mods.
so now do this:

cd /etc/apache2/mods-enabled
touch rewrite.load
gedit rewrite.load (you may use any editor to edit this file)

now paste this following line

LoadModule rewrite_module /usr/lib/apache2/modules/mod_rewrite.so

Then edit /etc/apache2/sites-available/000-default

Find the following

Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all

and change it to

Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
allow from all

and finally restart Apache

/etc/init.d/apache2 restart

Clean URL enabling in CentOS,

Step 1: a2enmod rewrite
Step 2 : change AllowOverride none to AllowOverride All in /etc/apache2/sites-available/
default

In Httpd,

Change AllowOverride none to AllowOverride All in /etc/httpd/conf/http.conf


Tuesday, September 15, 2009

VI EDITOR

Basic Cursor Movement

    From Command Mode

k Up one line

j Down one line

h Left one character

l Right one character (or use )

w Right one word

b Left one word

Entering, Deleting, and Changing Text
From Command Mode ,

  • i Enter text entry mode
  • x Delete a character
  • dd Delete a line
  • r Replace a character
  • R Overwrite text , press to end

Displaying Line Numbers

    From Command Mode

:set nu Display line numbers

:set nonu Hide line numbers

Exiting vi
  • To exit you must be in command mode-press if you are not in command mode
  • You must press after commands that begin with a : (colon)
From Command Mode

ZZ
Write (if there were changes), then quit
:wq
Write, then quit
:q Quit (will only work if file has not been changed)
:q! Quit without saving changes to file


More On Cursor Movement

From Command Mode

e Move to end of current word

$ Move to end of current line

^ Move to beginning of current line

+ Move to beginning of next line

- Move to beginning of previous line


G Go to last line of the file

:n Go to line with this number (:10 goes to line 10)


d Scroll down one-half screen

u Scroll up one-half screen

f Scroll forward one full screen

b Scroll backward one full screen


) Move to the next sentence

( Move to the previous sentence

} Move to the next paragraph

{ Move to the previous paragraph


H Move to the top line of the screen

M Move to the middle line of the screen

L Move to the last line of the screen


% Move to matching bracket: ( { [ ] } )


Entering Text Mode

From Command Mode

i Insert text before current character

a Append text after current character

I Begin text insertion at the beginning of a line

A Append text at end of a line

o Open a new line below current line

O Open a new line above current line


Commands and Objects

Format Example

operator number object c2w

number operator object 2cw


Operators

c change

d delete

y yank


Objects and Locations

w one word forward

b one word backward

e end of word

H, M, L top, middle, or bottom line on screen

), ( next sentence, previous sentence

}, { next paragraph, previous paragraph

^, $ beginning of line, end of line

/pattern/ forward to pattern



Replacing and Changing Text

From Command Mode

r Replace only the character under the cursor.
(Note: using r you remain in command mode.)

R Beginning with the character under the cursor,
replace as many characters on this line as you
want. (You are in overtype mode until you
press

cw Beginning with the character under the cursor,
change a word to whatever you type. (You are
in insert mode until you press )

c$ Beginning with the character under the cursor,
C change a line to whatever you type. (You are
in insert mode until you press )


Deleting Text

From Command Mode

x Delete a character

dw Delete an alphabetic word and the following space
(6dw deletes six words)

dW Delete a blank-delimited word and the following space

dd Delete a line (6dd deletes six lines)

d$ Delete all characters to the end of the line.
D

d} Delete all characters to the end of the paragraph.

:5,30d Delete lines 5 through 30


Deleted text goes into a temporary buffer that is replaced each time you delete (or copy) more text. The current contents of the buffer can be put back into your file.
Copying and Pasting Text

From Command Mode

yy Copy (yank) the current line

6yy Copy (yank) six lines, beginning with the current line

yw Copy the current word

p Put the text after the cursor position

P Put the text before the cursor position


Copied text goes into a temporary buffer that is replaced each time you copy (or delete) more text. Only the current contents of the temporary buffer can be put back into your file. As a result, when you use copy (y), use the put (p) command immediately.

A yank and put procedure using colon commands:

1. :5,10y Copy lines 5-10

2. Move cursor

3. :put Put after cursor

Other Useful Commands

From Command Mode

. Repeat last command

n. Repeat last command n number of times

J Join next line to current line

u Undo last single change

U Restore current line

~ Change letter's case (capital to lower and vice versa)


Buffers

Temporary Buffer

Deleted or copied text goes into a temporary unnamed buffer. The contents of the temporary buffer may be retrieved by using the p or P commands.

p Put words from temporary buffer after cursor or
put lines from temporary buffer below current line

P Put words from temporary buffer before cursor or
put lines from temporary buffer above current line


Lettered Buffers

There are 26 lettered buffers (a-z). Contents of a lettered buffer are saved until you copy or delete more characters into it, or until you quit your current vi session.


From Command Mode

"ayy Copy (yank) a line into buffer a

"Ayy Appends to buffer a

"a10yy Copies 10 lines into buffer a

"a10dd Deletes 10 lines of text into buffer a

"ap Put contents of lettered buffer a below the current line


Both temporary and lettered buffers last only for the current vi session.

Copying, Deleting, or Moving Text Using Line Numbers
* These commands start with a colon (:) and end with a or
* g shows the line number of the current line
* The basic form of colon commands is

:beginning_line, ending_line command destination

where destination is the line after which you want the text placed.


From Command Mode

:5,10 co 105 Copy lines 5-10 to the line after 105

:5,20 m $ Move lines 5-20 to end of file

:7,300 d Delete lines 7-300 (to buffer)


Searching for Text

From Command Mode

/text Search forward (down) for text (text can include spaces
and characters with special meanings.)

?text Search backward (up) for text

n Repeat last search in the same direction

N Repeat last search in the opposite direction

fchar Search forward for a charcter on current line

Fchar Search backward for a character on current line

; Repeat last character search in the same direction

% Find matching ( ), { }, or [ ]


Substitutions

The simplest way to do substitutions over a range of lines, or throughout the file, is to use the s colon command. The basic form of this command is the following:


:n1,n2s/old/new/gc

n1 is the beginning line

n2 is the ending line number

s means to substitute text matching the pattern (old)
with text specified by (new)

g (global) is optional. It indicates you want to substitute
all occurrences on the indicated lines. If you use
g, the editor substitutes only the first occurrence
on the indicated lines.

c (confirm) is optional. It indicates you want to confirm
each substitution before vi completes it.


From Command Mode

:%s/old/new/g Substitutes old with new throughout the file

:.,$s/old/new/g Substitutes old with new from the current
cursor position to the end of the file

:^,.s/old/new/g Substitutes old with new from the beginning
of the file to the current cursor position

:& Repeats the last substitute (:s) command


ADVANCED VI

1. Writing to and Reading from Files

From Command Mode

:w file Write current file to file

:w>>file Append current file to file

:5,10w file Write lines 5 through 10 to file

:5,10w>>file Append Lines 5 through 10 to file

:r file Read a copy of file into current file

:!ls See a list of files in your current directory


More About Options

From Command Mode-within vi for the current file only

:set all Display all options

:set Display current settings of options

:set nooption Unset option

:set ai Set Auto Indentation during text entry

:set ic Set Ignore Case during searches

:set nu Show line Numbers

:set sm Show Matching ( or { when ) or } is entered

:set wm=10 Set Wrap Margin 10 spaces from right edge of screen


Customizing vi Sessions

Options can be set four ways:
1. During a vi session

:set nu



2. In a .exrc file in your home directory.

Sample contents of a .exrc file

set nu
set ai
set wm=10





TIPS AND TRICKS

1. Making vi an Editor in Pine

1. In your home directory, type: vi .pinerc

2. Find the line that reads


editor=


3. Change it to read


editor=vi


4. Write and quit the file. (ZZ or :wq)

5. Start Pine

6. In Pine in Compose mode, when you are ready to enter message text, you will see there is an option available called Alt Edit. (Alternate Editor). To evoke the Alternate Editor mode, press: _

When finished editing in vi, exit vi and you will be returned to the compose screen.

2. vi-ing More Than One File

You can edit more than one file at a time with vi.

From The Unix Shell Prompt

vi file1 file2 vi two (or more) files at the same time

From Command Mode

:n Move to file2 from file1

:rew Rewind back to file1

:e! Restore original file1 file2 (start all over)

ZZ Save and quit file. (Must be done for each file.)


Issuing Shell Commands From vi

You can issue a single shell command while in the vi editor. For example, to list the files in your directory (ls), follow these steps:

From Command Mode

:w Write changes to your file (just in case).

:!ls List contents of your current directory on the screen.

Press to return to vi.


You can issue many shell commands by temporarily leaving the vi editor.

From Command Mode

:w Write changes to your file.

:sh Return to the shell to enter a number of commands
without leaving vi.

Press d to return to vi editing.