.vimrc

You have the option of creating a .vimrc file in your home directory. This file can customize your editing environment. If you use a Mac, you should have these lines in your .vimrc.

syntax on
set et
set tabstop=4

This file runs every time you open a session with vi. The three lines present in the example enable syntax coloring (you want this), expand tabs into spaces (for Python sanity), and set your tabstop to 4 spaces. Note: Type this exactly as shown; do not put spaces around the = or you will get nastygrams whenever you open vi.

If you want line numbers by default, just add this line.

set number

If you find yourself using several colon commands at the start of a session, add them to your .vimrc.

Visual Mode

The third mode of the vi editor, visual mode is actually three modes in one: line mode, character mode, and block mode. To enter line mode from command mode, hit V; to enter character mode hit v, and to enter block mode, hit Control-v. You can exit any of these by hitting the ESC key; this places you back in command mode. Visual mode has one purpose: it allows you to select text using keyboard commands; you may then perform various operations on these selections. First, let us see the selection mechanism at work.

Go into a file and position your cursor in the middle of a line. Hit v to enter visual character mode. Now use the arrow keys; notice how the selected text changes in response to arrow key movement. Try entering gg and G and see what happens. Hit ESC to finish. Now enter visual mode and use the / search facility to search up something on the page. What happens? Search backward and try that too.

Now enter visual line mode by hitting V; now try the keystrokes we just indicated and see how the selection behaves. This mode only selects whole lines.

Finally if you enter Control-V and you enter visual block mode, you can select a rectangular block of text from the screen by using the keyboard.

Now let’s see what you can do with these selections. First let us look at character and line mode, as block mode behaves a little differently. You can cut the selected text to Mabel by hitting d. You can yank it into Mabel by hitting y. Upon typing either command, you will be put back into command mode. Once any text is placed into Mabel, you can paste it with p as you would any other text yanked there. If you hit c, the selection will be deleted and you will be in insert mode so you can change the text. The stricken text is cut to Mabel.

In block mode, things are a little different. If you hit d, the selected block will be deleted, and the lines containing it shortened. The stricken text is cut to Mabel. If you hit y, the block will be yanked just as in any other visual mode, and its line structure will be preserved. If you hit c, and enter text, the same change will be made on all line selected provided you do not hit the ENTER key. If you do, the change will only be carried out on the first line. You can insert text rather than change by hitting I, entering your text, and then hitting ESC. If the text you enter has no newline in it, the same text will be added to each line; if it has a newline, only the first line is changed.

If you hit r then any character in any visual mode, all selected characters are changed to that character.

Here is a very common use for character or line visual mode. Suppose you are editing a document and the lines end in very jagged fashion. This sort of thing will commonly happen when maintaining a web or if you are editing a LaTeXdocument such as this one, where the page that is subjected to repeated edits. Use visual mode to select the affected paragraphs and hit gq (think Gentleman’s Quarterly) and your paragraphs will be tidied up.

You can also do search-and-replace using visual mode to select the text to be acted upon. Simply select the text in visual mode. Then hit

: s/outText/inText/g

to perform the substitution in the selected text. For example if you select text in visual mode and change every w to a v, you will see this.

:'<,'>s/w/v/g

The <,'> is a quirky way of indicating you are doing a visual-mode search-replace operation.

Replace Mode

In vi if you hit r then a character, the character under the cursor is replaced with the character you it. If you hit R, you are in replace mode, and any test you type “overruns” existing text. Experiment with this in a file you don’t care about.

Replace mode is fabulous for making ASCII art such as this.

< Galactophagy >
 -------------- 
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||

You should play around with this. Do a Google search to learn about ASCII art.

Copy Paste from a GUI

You can copy and paste with the mouse in a window or between windows. The way you do it varies by OS so we will quickly discuss each. If you are pasting into a file you are editing with vi, it is a smart idea to use the colon command :set paste. This will prevent the “mad spraying” of text. For certain types of files, this turns off automatic indentation or formatting. You can use :set nopaste to turn off the paste mode.

Windoze

If you are copying from a Windoze application into a terminal window, select the text you want to copy and use control-C in the usual way. This places the text in your Windoze system clipboard. Now go into your terminal window and get into insert mode where you want to paste. It is also wise, in command mode, to enter :set paste. Right-click to paste the contents of your system clipboard into the terminal window. Many of you will say, “Why did the beginning of the text I copied get cut off or why didn’t it appear at all?” This will occur if you are not in insert mode when you paste. It is important to be in insert mode before pasting to avoid unpleasant surprises. If this happens, hit ESC then u in command mode. The u command undoes the last vi command. Then you can take a fresh run at it.

If you are copying from a terminal window, select the text you wish to copy; PuTTY will place the text in your system clipboard. Then go into the window in which you wish to paste it. If the window is another terminal, get into insert mode and right-click on the mouse. If it’s a Windoze app, use control-V as you usually do.

Mac

Use command-c to copy and command-v to paste to or from a terminal window, just as you would with any other mac app. Mac gets this right.

Linux

If you use a Linux box, use control-shift-C for copying in terminal windows and control-shift-V for pasting to terminal windows.

A Reprise: A Warning About autoindent and paste

Before pasting with the mouse make sure you have autoindent turned off. Otherwise, your text will “go mad and spray everywhere,” especially if you are copying a large block of text with indents in it. You can turn autoindent on with :set autoindent and off with :set noautoindent. This feature can be convenient when editing certain types of files. You can use the command :set paste to turn off all smart indentation; when finished use :set nopaste to set things back to their original state.

A Warning abut Line Numbers

If you copy-paste to a GUI, line numbers will get copied. To prevent this from happening, use the colon command :set nonu before copying.

Experiment with these new techniques in some files. Deliberately make mistakes and see what happens. Then when you are editing files, you will know what to expect and how to recover.

There are a lot of excellent tutorials on vi on the web; avail yourself of these to learn more. Remember the most important thing: you never stop learning vi! Here are some useful vi resources on the web.

Permissions

Now we will see how you can use permissions to control the visibility of your files on the system. You are the owner of your home directory and all directories and files it contains. This is your “subtree” of the system’s directories belonging to you. You may grant, revoke or configure permissions for all the files and directories you own as you wish. UNIX was designed with the fundamental idea that your data are your property, and you can control what others see of them.

There are three layers of permission: you, your group, and others. You is letter u, your group is letter g and others is letter o. There are three types of permission for each of these: read, write and execute. Read means that level can read the file, write means that level can execute the file, and execute means that level can execute the file. In the example above, the file bar has the permission string

 -rw-rw-r--

which means the following.

For the user to execute this file, use the chmod command as follows

unix> chmod u+x bar

The u(ser’s, that’s you) permission changed to allow the user to execute the file.

If you do not want the world to see this file you could enter

unix> chmod o-r bar

and revoke permission for the world to see the file bar. Since you are the owner of the file, you have this right. In general you can do

$  chmod (u or g or o)(+ or -)(r or w or x) fileName

to manage permissions. You can omit the u, g or o and the permission will be added or deleted for all three categories. In the next subsection, we discuss the octal representation of the permissions string. This will allow you to change all three levels of permissions at once quickly and easily.

The Octal Representation

There is also a numerical representation for permissions. This representation is a three-digit octal (base 8) number. Each permission has a number value as follows.

We show how to translate a string in this example.

-rw-r--r--
  6  4  4

The only way to get a sum of 6 from 1,2 and 4 is 4 + 2; therefore, 6 is read-write permission. The string translates into three digits 0-7; this file has 644 permissions. It is a simple exercise to look at all the digits 0-7 and see what permissions they convey.

We show some more examples of chmod at work. Look at how the permissions change in response to the chmod commands. Suppose we are a directory containing one file named empty, which has permission string -rw-r–r–, or 644. We begin by revoking the read permission from others.

unix> chmod o-r empty

We now list the files in the directory

unix> ls -l
total 0
-rwxr----- 1 morrison morrison 0 2008-08-26 10:52 empty
unix> ls
empty

We can now restore the original permissions all at once by using the octal number representation for our permissions.

 chmod 644 empty
unix> ls -l
total 0
-rw-r--r-- 1 morrison morrison 0 2008-08-26 10:52 empty

Notice what happens when we try to use a 9 for a permission string.

unix> chmod 955 empty
chmod: invalid mode: ‘955’
Try ‘chmod --help’ for more information.

Try typing the chmod –help command at your prompt and it will show you some useful information about the chmod command. Almost all UNIX commands have this help feature.

Directories must have executable permissions, or they cannot be entered, and their contents are invisible. Here we use the -a option on ls. Notice that the current working directory and the directory above it have execute permissions at all levels. Try revoking execute permissions from one of your directories and attempt to enter it with cd; you will get a Permission Denied nastygram from the operating system.

unix> ls -al
total 20
drwxr-xr-x 2 morrison faculty 4096 2008-10-17 11:51 .
drwx--x--x 9 morrison faculty 4096 2008-10-16 08:39 ..
-rw-r--r-- 1 morrison faculty 0 2008-10-17 11:51 empty
unix>

Here we shall do this so you can bear witness

unix> mkdir fake
unix> chmod u-x fake
unix> cd fake
bash: cd: fake: Permission denied
unix>

Assigning 600 permissions to a file is a way to prevent anyone but yourself from seeing or modifying that file. It is a quick and useful way of hiding things from public view. Later, when you create a web page, you can use this command to hide files or directories in your website that you do not want to be visible.

Globbing and Permissions

You can use globbing to change permissions on a glob of files. For example,

chmod 644 *.html

gives all HTML files in your cwd 644 permissions.

The Man

The command man is your friend. Type man then your favorite UNIX command to have its inner secrets exposed! For example, at the UNIX prompt, enter

unix> man cat

This brings up the man(ual) page for the command cat. A complete list of options is furnished. Notice that some of these have the , or long form.

CAT(1)                User Commands                   CAT(1)

NAME
       cat - concatenate files and print on the standard output

SYNOPSIS
       cat [OPTION] [FILE]...

DESCRIPTION
       Concatenate FILE(s), or standard input, to standard output.

       -A, --show-all
              equivalent to -vET

       -b, --number-nonblank
              number nonblank output lines

       -e     equivalent to -vE

       -E, --show-ends
              display $ at end of each line

       -n, --number
              number all output lines

       -s, --squeeze-blank
              never more than one single blank line

       -t     equivalent to -vT

       -T, --show-tabs
              display TAB characters as ^I

       -u     (ignored)

       -v, --show-nonprinting
              use ^ and M- notation, except for LFD and TAB

       --help display this help and exit

       --version
              output version information and exit

       With no FILE, or when FILE is -, read standard input.

EXAMPLES
       cat f  g
              Output f's contents, then standard input, 
              then g's contents.

       cat    Copy standard input to standard output.

AUTHOR
       Written by Torbjorn Granlund and Richard M. Stallman.

REPORTING BUGS
       Report bugs to <bug-coreutils@gnu.org>.

COPYRIGHT
       Copyright © 2006 
       Free Software Foundation, Inc.  
       This  is  free software.  You may redistribute 
       copies of it under the terms of the GNU General 
       Public License <http://www.gnu.org/licenses/gpl.html>.  
       There is NO WARRANTY, to the extent permitted by law.
SEE ALSO
       The full documentation for cat is maintained 
       as a Texinfo manual.  If the info and cat 
       programs are  properly installed at your site, 
       the command info cat should give you access 
       to the complete manual.

cat 5.97     August 2006                       CAT(1)

You can see here that even humble cat has some options to enhance its usefulness. Here is cat at work on a file named trap.py.

unix> cat trap.py
def trap(a, b, n, f):
    a = float(a)
    b = float(b)
    h = (b - a)/n
    list = map(lambda x: a + h*x, range(0,n+1))
    tot = .5*(f(a) + f(b))
    tot += sum(map(f, list[1:n]))
    tot *= h
return tot
def f(x): 
    return x*x
print trap(0,1,10,f)
print trap(1,2,100,f)

Using the -n option causes the output to have line numbers.

 cat -n trap.py
    1 def trap(a, b, n, f):
    2     a = float(a)
    3     b = float(b)
    4     h = (b - a)/n
    5     list = map(lambda x: a + h*x, range(0,n+1))
    6     tot = .5*(f(a) + f(b))
    7     tot += sum(map(f, list[1:n]))
    8     tot *= h
    9     return tot
   10 def f(x): 
   11   return x*x
   12 print trap(0,1,10,f)
   13 print trap(1,2,100,f)
unix>

View the manual pages on commands such as rm, ls chmod and cp to learn more about each command. Experiment with the options you see there on some junky files you create and do not care about losing.

Exercises

  1. Use the man command to learn about the UNIX commands more and less. You will see here, that in fact, less is more!

  2. Use the man command to learn about the UNIX commands head and tail. Can you create a recipe to get the first and last lines of a file?

  3. What does the ls -R command do?

Lights, Camera, Action! Where’s the Script?

Sometimes you will find yourself doing certain chores repeatedly. An intelligent question to ask is, “Can’t I just save this list of commands I keep typing over and over again in a file?”

Happily, the answer to this is “yes.” It’s called writing a shell script. In its simplest form, a shell script is just a list of UNIX commands in a file. We will see how to make one of these and run it. Begin by creating this file, greet.sh.

#!/bin/bash
echo Hello, $LOGNAME!
echo Here is the calendar for this month:
cal

Type commands you see in this file into your shell. You will see this.

unix> echo Hello, $LOGNAME!
Hello, morrison!
unix> echo Here is the calendar for this month:
Here is the calendar for this month:
unix> cal
    January 2020      
Su Mo Tu We Th Fr Sa  
          1  2  3  4  
 5  6  7  8  9 10 11  
12 13 14 15 16 17 18  
19 20 21 22 23 24 25  
26 27 28 29 30 31     

Now give this file execute permissions like so.

unix> chmod +x greet.sh

Now run it (note the slash-dot).

unix> ./greet.sh
Hello, morrison!
Here is the calendar for this month:
    January 2020      
Su Mo Tu We Th Fr Sa  
          1  2  3  4  
 5  6  7  8  9 10 11  
12 13 14 15 16 17 18  
19 20 21 22 23 24 25  
26 27 28 29 30 31     

We can make this process even better. If you don’t have one, create a directory named bin in your home directory. Then open the dotfile .bash_profile and add this line to it.

export PATH=$PATH:"/Users/morrison/bin"

Replace the /Users/morrison with the path to your home directory. Put your shiny new script into this directory. Then you don’t need the slash-dot any more unless you are in the bin directory. This has the benefit of allowing you to run the script from anywhere in the file system.

Terminology Roundup