Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 67

Introduction

This document is only a brief introduction to UNIX and does not include information on how to use all of its capabilities. Since this introduction to UNIX is brief, we encourage you to seek out more detailed introductory information. Information Systems offers free Short Courses on UNIX that you can sign up for. The Computing Resource Area, located in B40 in the basement of Fondren Library, has a number of very good introductory books on UNIX available for checkout. These books go into more detail and cover more of the operating system than will be covered in this document. You can also purchase some introductory UNIX books at the Rice Campus Store or almost any local bookstore with a computing section. This document introduces you to the basics of UNIX, including:

How to get started Shell and Commands File structures Directories

There are several variants of UNIX on the Rice campus; the type used most on Information Systems supported networks is from Sun Microsystems. Therefore, although the information concerning the UNIX operating system presented here is not limited to Sun workstations, it will focus on them. Information Systems maintains groups of machines for different groups of users; these groups of machines are known as domains. The major Information Systems domains are Owlnet, the Rice UNIX Facility (RUF), and Information Systems administration. Other departments or divisions may have their own domains, such as Computer Science or Electrical and Computer Engineering. Accounts in one domain are not valid on machines of other domains. Every workstation is labeled with its name and domain. If you have an Owlnet account, use the workstations or terminals in A121 or B223 Abercrombie, 241 Mechanical Engineering, 102 Ryon Lab, 105 Mudd, 221 Physics, or the workstations at your residential college..

What is UNIX?
UNIX is a powerful computer operating system originally developed at AT&T Bell Laboratories. It is very popular among the scientific, engineering, and academic communities due to its multi-user and multi-tasking environment, flexibility and portability, electronic mail and networking capabilities, and the numerous programming, text processing and scientific utilities available. It has also gained widespread acceptance

in government and business. Over the years, two major forms (with several vendor's variants of each) of UNIX have evolved: AT&T UNIX System V and the University of California at Berkeley's Berkeley Software Distribution (BSD). This document will be based on the SunOS 4.1.3_U1, Sun's combination of BSD UNIX (BSD versions 4.2 and 4.3) and System V because it is the primary version of UNIX available at Rice. Also available are Solaris, a System V-based version, and IRIX, used by Silicon Graphics machines.

UNIX Layers
When you use UNIX, several layers of interaction are occurring between the computer hardware and you. The first layer is the kernel, which runs on the actual machine hardware and manages all interaction with the hardware. All applications and commands in UNIX interact with the kernel, rather than the hardware directly, and they make up the second layer. On top of the applications and commands is the command-interpreter program, the shell, which manages the interaction between you, your applications, and the available UNIX commands. Most UNIX commands are separate programs, distinct from the kernel. A final layer, which may or may not be present on your system, is a windowing system such as X. The windowing system usually interacts with the shell, but it can also interact directly with applications. The final "layer" is you, the user. You will interact with the entire operating system through just the shell, or through a combination of the shell and the window system. The figure below gives a visual representation of the layers of UNIX.

FIGURE 1. UNIX Layers

Basic UNIX Elements


You need to be familiar with six basic elements of UNIX. They are: commands, files, directories, your environment, processes, and jobs. Commands are the instructions you give the system to tell it what to do. Files are collections of data that have been given filenames. A file is analogous to a container in which you can store documents, raw data, or programs (it can contain only one kind of data at a time). A single file might contain the text of a research project, statistical data, or an equation processing formula. Files are stored in directories. A directory is similar to a file cabinet drawer that contains many files. A directory can also contain other directories. Every directory has a name, like files. Your environment is a collection of items that describe or modify how your computing session will be carried out. It contains things such as where the commands are located and which printer to send your output to. A command or application running on the

computer is called a process. The sequence of instructions given to the computer from the time you initiate a particular task until it ends it is called a job. A job may have one or more processes in it. We will explore each of these elements in a little greater detail later on, but first you need to learn how to get on to your system.

Logging In and Out


Getting the Login Prompt
Before you can start using the system you must login to it. The method that you use to login varies depending on the type of device that you are using to login. Read the section below that is appropriate for you and then read the section, Entering Your Userid and Password.

TTY Terminal
If you are using a TTY terminal (a TTY is line-at-a-time oriented as opposed to page oriented) and the screen is blank, you only need to press RETURN and a login prompt should appear on the screen.

Workstation
If you are using a workstation, you may see a dark screen with a brief message similar to this:
chub, 4:20 pm, idle 2h 53m (Press ^C)

Press ^C (control-C) and you will see the prompt


chub login:

Almost every login prompt includes the workstation name before the word "login."

X Terminals
If the display features a box in the center of the screen with text similar to that in the figure below, then you are using a workstation that is configured to run a windowing system called the X Window system. These machines are called X terminals. (For more information on the X Window system, see the Information Systems document, UNIX 2, Introduction to the X Window System.).

FIGURE 2. X Terminal Login Window If the screen is entirely black, then a screen-saving program is running automatically to protect the monitor from damage. Moving the mouse or pressing the RETURN key should "wake up" the display. (If you see the words "This screen has been locked..." then

someone else is using the workstation, but they are temporarily away from their seat. Look for an unoccupied machine.) Move the mouse until the cursor (a black `X') is on top of the white box.

Entering Your Userid and Password


When you picked up your account information, you were given a userid and a password. This combination of information allows you to access your account. Type your userid using lower-case letters, then press the RETURN key. It is very important that you use lower-case letters for your userid. If you make a typing mistake, you can correct it by pressing the DELETE key once for each character you wish to erase. You must make your corrections before you press the RETURN key. If the text you are typing appears in upper-case, see the section, Troubleshooting. After you have entered your userid, the system will prompt you for your password (by displaying the word "Password:" if it is not already on the screen, or by moving the cursor behind the word "Password:" already on your screen). Enter your password and press the RETURN key. Notice that the system does not show or "echo" your password as you type it. This prevents other people from learning your password by looking at your screen. If you receive a message similar to "Login failed, please try again," you may have typed your userid or password incorrectly. Try again, making sure to type in your userid and password correctly. If you are still having problems, go to the Consulting Center in 103 Mudd Lab and ask for help. When you have successfully logged on, the system will pause for a moment, and then display a few lines telling you when and from which machine you last logged on, and any messages from the system administrator. On X terminals, you will get a window containing system information. After reading it, use the left mouse button click on either the "Help" or "Go Away" button, depending on what you want. Help puts you into a help system; Go Away allows you to begin your work. Your new account is provided with a set of command procedures which are executed each time you log in. You can change part of your UNIX environment by changing these setup files (accounts on Information Systems supported systems are set up to produce a default environment). For further information, check the Sun manual SunOS User's Guide: Customizing Your Environment, available for building use only in the Operations Center, 109 Mudd Lab. The system will then display the command prompt. The prompt signals that the system is ready for you to enter your next command. The name of the workstation followed by a percent sign (%) forms the command prompt (e.g. chub%). Once you finish typing a command, you must always press RETURN to execute it.

Logging Out
Workstations and TTY Terminals
To end a work session, you must explicitly log out of a UNIX session. To do this, type logout at the command prompt. Once you have logged out, the system will either display the login prompt again or begin executing a screen saver program. You should never turn a workstation off. Turning off a terminal does not necessarily log you out. If you are having trouble logging out, see the section, Troubleshooting.

X Terminals
To log out of the X Window system from an X terminal, move the cursor into the console window (it is labeled "console"), type the command exit, and press RETURN. If you try to use the logout command in the console window, you will receive the message, "Not in login shell." If you used the startx command to start the X session (if you are working on a Sun workstation, for example), after you end the X session you will have the option to remain logged on by pressing CTRL-C within three seconds after exiting. If you do so, the X windows and background vanish, returning you to a text-only display. At the prompt, type exit to log out.

Changing Your Password


You can change your password at any time. You should change it the first time that you log in, and we recommend that you change it on a regular basis. At the command prompt, type passwd.You will be prompted to enter your old password and be asked twice to enter your new password. Neither your old nor new password will appear on the screen as you type. In order to be accepted, your password must meet the following conditions: 1. It must be at least seven characters long. 2. It must not match anything in your UNIX account information, such as your login name, or an item from your account information data entry. 3. It must not be found in the system's spelling dictionary unless a character other than the first is capitalized. It must not have three or more consecutively repeated characters or words in the dictionary contained within it. For example, changing your password from Kat899 to B00z00e will look similar to the following example, except that the keystrokes for you old and new password will not be echoed on the screen.

passwd
current password: Kat899 New password (? for help): B00z00e New password (again): B00z00e Password changed for userid

On many systems, the password change does not take effect immediately, even though you have finished with the passwd command. It can take upwards of an hour for the system to install the new password, due to the scheduling of the password changing process. Thus you should be prepared to use your old password to login again shortly after changing it. If you should ever forget your password, you can go to the Information Desk in 103 Mudd Lab and request that a new password be generated for you. You will need to bring your Rice ID card with you to pick up your new password.

UNIX Commands
The UNIX Shell
Once you are logged in, you are ready to start using UNIX. As mentioned earlier, you interact with the system through a command interpreter program called the shell. Most UNIX systems have two different shells, although you will only use one or the other almost all of the time. The shell you will find on Information Systems supported networks is the C shell. It is called the C shell because it has syntax and constructs similar to those in the C programming language. The C shell command prompt often includes the name of the computer that you are using and usually ends with a special character, most often the percent sign (%). Another common shell is the Bourne shell, named for its author. The default prompt for the Bourne shell is the dollar sign ($). (If the prompt is neither one of these, a quick way to check which shell you are using is to type the C shell command alias; if a list appears, then you are using the C shell; if the message, "Command not found" appears, then you are using the Bourne shell). Modified versions of these shells are also available. TC shell (tcsh) is C shell with file name completion and command line editing (default prompt: >). The GNU Bourne-Again shell (bash) is basically the Bourne shell with the same features added (default prompt: bash$). In addition to processing your command requests, UNIX shells have their own syntax and control constructs. You can use these shell commands to make your processing more efficient, or to automate repetitive tasks. You can even store a sequence of shell commands in a file, called a shell script, and run it just like an ordinary program. Writing shell scripts is a topic discussed in the class notes for the UNIX III-Scripts Short Course.

About UNIX Commands

UNIX has a wide range of commands that allow you to manipulate not only your files and data, but also your environment. This section explains the general syntax of UNIX commands to get you started. A UNIX command line consists of the name of the UNIX command followed by its arguments (options, filenames and/or other expressions) and ends with a RETURN. In function, UNIX commands are similar to verbs in English. The option flags act like adverbs by modifying the action of the command, and filenames and expressions act like objects of the verb. The general syntax for a UNIX command is: command [-flag options] file/expression The brackets around the flags and options are a shorthand way to indicate that they are often optional, and only need to be invoked when you want to use that option. Also, flags need not always be specified separately, each with their own preceding dash. Many times, the flags can be listed one after the other after a single dash. Some examples later on will illustrate this concept. You should follow several rules with UNIX commands: 1. 2. 3. 4. 5. UNIX commands are case-sensitive, but most are lowercase. UNIX commands can only be entered at the shell prompt. UNIX command lines must end with a RETURN. UNIX options often begin with a "-" (minus sign). More than one option can be included with many commands.

Redirecting Input and Output


UNIX maintains a couple of conventions regarding where input to a program or command comes from and output from that program or command goes. In UNIX, the standard input is normally the keyboard, and the standard output is normally the screen. UNIX is very flexible, and it allows you to change or redirect where the input comes from and where the output goes. First, any command that would normally give results on the screen can be directed instead to send the output to a file with the ">" (output redirection) symbol. Thus, date > file directs the system to put the output from the date command, which merely reports the time and date as the system knows it, into the file namedfile rather than printing it to your screen. One thing to keep in mind about ">" is that each successive redirection to a particular file may overwrite all of the previously existing data in that file, though this is unlikely. Another redirection is "<," which tells the command to take its input from a file rather than from the keyboard. For example, if you have a program that requires data input from the keyboard, you may find that you have to type the same data a large number of times in the debugging stage of program development. If you put that data in a file and direct

the command to read it from there you will only have to type the data once, when you make the data file. program < datafile If you do this, you would see the same response from program as if you had typed the data in from the keyboard when requested. You can also combine both kinds of redirection as in, program < datafile > outputfile The data in the file datafile will then be used as input for program and all output will be stored in outputfile. If you want to accumulate output from different sources in a single file, the symbol ">>" directs output to be appended to the end of a file rather than replacing the previous (if any) contents, which the single ">" redirection will do. A final I/O redirection is the pipe symbol, "|." The "|" tells the computer to take the output created by the command to the left of it and use that as the input for the command on the right. For example, we could type:

date | program This would use the output of the date command as input to another program.

Getting On-Line Help with Commands


The standard on-line help facility available with UNIX is electronic reference manuals, known as the man pages, and you access them with the man command. man command-name The man pages provide an in-depth description of command-name, with an explanation of its options, examples, and further references. The information is an electronic duplicate of the paper reference manual pages. Use the man command for explicit information about how to use a particular command. Use the -k option to search for a keyword among the one line descriptions in the help files. man -k keyword The command apropos serves exactly the same function as man -k and is used in the same way. You can read about the man command itself using man. Type man man at the prompt. The UNIX reference manual is divided into eight numbered sections: 1. General User Commands 2. System Calls 3. User-level Library Functions

4. 5. 6. 7. 8.

Device Drivers, Protocols File Formats Games (rarely available) Document Preparation System Administration

You can see the command summary for each section by typing: man # intro where # is one of the eight section numbers. In addition, other applications that reside on your system may have man pages. These pages can often be called up in the same manner as the operating system man pages.

Case Sensitivity
UNIX is a case sensitive operating system. It treats lower-case characters differently than upper-case characters. For example, the files readme, Readme, and README would be treated as three different files. Most command names and files are entirely in lower-case. Therefore, you should generally plan to type in lower-case for most commands, command line arguments, and option letters.

Special Keys and Control Characters


UNIX recognizes special keys and control-character key strokes and assigns them special functions. A special key such as the DELETE key is usually mapped to the ERASE function, which erases the most recent character that you typed on the current line. A control-keystroke such as CTRL-C is invoked by holding down the key labeled CONTROL and pressing the "c" key (in the same manner that you hold down the SHIFT key and press the "c" key to generate a capital C). The notation for control characters is usually ^C or CTRL-C. Some standard special keys and control characters are summarized below. TABLE 1. Special Keys and Control Characters
SPECIAL KEY FUNCTION/DESCRIPTION DELETE Acts as a rubout or erase key. Pressing DELETE once will backup and erase one character, allowing you to correct and retype mistakes. BACKSPACE the backspace key, display. This key is sometimes used as the rubout key instead of DELETE key. Otherwise, it is mapped as a which generates a ^H on the

CTRL-U the line

^U erases the entire command line. It is also called

kill character. CTRL-W ^W erases the last word on the command line. CTRL-S ^S stops the flow of output on the display. CTRL-Q ^Q resumes the flow of output stopped by CTRLS. CTRL-C ^C interrupts a command or process in progress and returns to the command line. This will usually work; if it doesn't, try typ ing several ^C's in a row. If it still doesn't work, try typing ^\, q (for quit), exit, ^D, or ^Z. CTRL-Z ^Z suspends a command or process in progress. CTRL-D ^D generates an end-of-file character. It can be used to terminate input to a program, or to end a session with a shell. CTRL-\ ^\ quits a program and saves an image of the program in a file called core for later debugging.

A Selected Command List


The next few pages summarize many of the basic UNIX commands you need to get started. For further details on UNIX commands not discussed (or that are beyond the scope of this introductory document), consult the system manuals available in the Operations Center, 109 Mudd Lab, and in the labs, or get some practice using the man command.

Setup and Status Commands


COMMAND logout passwd stty date finger ps env set alias history PURPOSE end your UNIX session change password by prompting for old and new passwords set terminal options display or set the date display information about users display information about processes display or change current environment C shell command to set shell variables C shell command to define command abbreviations C shell command to display recent commands

File and Directory Commands


COMMAND cat more most mv cp rm ls mkdir rmdir cd pwd du chmod file PURPOSE concatenate and display file(s) paginator - allows you to browse through a text file more versatile paginator than more move or rename files copy files remove files list contents of directory make a directory remove a directory change working directory print working directory name summarize disk usage change mode (access permissions) of a file or directory determine the type of file

Editing Tools
COMMAND PURPOSE

vi screen oriented (visual) display editor diff show differences between the contents of files grep search a file for a pattern sort sort and collate lines of a file (only works on one file at a time) wc count lines, words, and characters in a file look look up specified words in the system dictionary awk pattern scanning and processing language

Formatting and Printing Commands


COMMAND lpq lpr lprm enscript PURPOSE view printer queue send file to printer queue to be printed remove job from printer spooling queue converts text files to POSTSCRIPT format for printing

Program Controls, Pipes, and Filters


COMMAND PURPOSE

CTRL-C interrupt current process or command CTRL-D generate end-of-file character CTRL-S stop flow of output to screen CTRL-Q resume flow of output to screen CTRL-Z suspend current process or command jobs lists background jobs sleep suspend execution for an interval kill terminate a process nice run a command at low priority renice alter priority of running process & run process in background when placed at end of command line > redirect the output of a command into a file >> redirect and append the output of a command to the end of a file < redirect a file to the input of a command >& redirect standard output and standard error of a command into a file (C shell only) | pipe the output of one command into another THE FOLLOWING COMMANDS ARE NOT AVAILABLE WITH THE BOURNE SHELL bg fg !! !$ run a current or specified job in the background bring the current or specified job to the foreground repeat entire last command line repeat last word of last command line

Other Tools and Applications


COMMAND mail bc man PURPOSE electronic mail desk calculator print UNIX manual page to screen

Files
About UNIX Files

Now that you understand UNIX commands, let's discuss the objects manipulated by most commands: files. As we said before, all files have a filename, and UNIX imposes few restrictions on filenames. This makes it easy for you to name your files so that you can easily recognize their contents. You will find it useful to adopt names and classes of names that indicate how important each file is and what connection it has with other files. For example, temporary files used to test commands and options could all begin with a "t." A filename can be up to 256 characters long, consisting of any alphanumeric character on the keyboard except the "/". In general, you should keep your filenames relatively short (to reduce typing effort) and use normal lower-case characters such as letters, numbers, periods and underscores. For instance, if your program calculates employee paychecks, you might call it payroll, or if your file is a research paper on Frank Lloyd Wright, you might call it wright. Do not include blanks in your filenames as they will make it very difficult for you to work with the file. If you do wish to separate letters in a filename, use the underscore ("_") character (as in wright_paper) or the hyphen ("-") character. Remember that UNIX is case sensitive, which means it recognizes the difference between upper-case and lower-case letters. For instance, Wright and wright would refer to two different files. When you place a single period in the middle of a filename, the part after the period is commonly referred to as an extension or suffix and usually indicates what type of information is stored in the file. You may use any extension desired; a text file might have the extension .txt or .text; a note may have the extension .note, and so forth. UNIX does not require extensions; they are intended to help identify similar types of files. Since some UNIX programs (especially compilers) look for certain standard extensions, it is common practice to use the following conventions: .h for header files, .c for C source files, .f for FORTRAN, .p for Pascal, and .s for assembler source files. So the file wright.txt indicates a text file whereas the file payroll.c indicates a C program called payroll. For more information on programming conventions, see the section, Additional Resources. Some UNIX files begin with a period, for example, .cshrc or .login. Files that begin with a period will not appear in a normal directory listing and are usually UNIX environment and application setup files. A large grouping of files and directories is referred to as a file system. File systems are related to the disk size and structure, and to the internal structure of UNIX. What you should remember is that users' files and directories are usually on a different file system than the system's files and directories. If the number of users is large, as on Owlnet, the user files and directories may be on more than one file system.

Creating Files
Many files are created using a text editor. A text editor is a program that allows you to enter and save text. You can also use a text editor to manipulate saved text through corrections, deletions, or insertions. The main text editors on Information Systems managed networks are vi, GNU Emacs, Pico, and aXe. (Note: vi is included with every

UNIX system, but GNU Emacs is commonly installed separately by system managers. aXe is only available if you are using the X Window system.) You should learn how to use at least one of these tools. Information Systems has tutorial documents on each of these editors. Please see the section, Additional Resources, for information on the tutorials. You can create a file without a text editor by using the cat command (short for concatenate) and the ">" (redirect output) symbol. To create a file using the cat command, type: cat > new-filename where new-filename is the name you wish to give the file. The command cat generally reads in a file and displays it to standard output. When there is no filename directly following the command, cat treats standard input as a file. The ">" symbol will redirect the output from cat into the new filename you specify. cat will keep reading and writing each line you type until it encounters an end-of-file character. By typing CTRL-D on a line by itself, you generate an end-of-file character. It will stop when it sees this character. Try it, using this example as a guide: cat > practice When you reach the end of each line, press the RETURN key. You can only correct mistakes on the line you are currently typing. Use the DELETE key to move the cursor back to the mistake and then retype the rest of the line correctly. When you have completed the last line, press RETURN and type CTRL-D.

Displaying Files
Now that you have created a file, you can display it one of several ways. You could use the cat command. Just type cat followed by the name of the file that you want to see. cat practice Sometimes the files you want to view are very long. When using the cat command, the text will scroll by very quickly. You can control the flow of text by using CTRL-S and CTRL-Q. CTRL-S stops the flow of text and CTRL-Q restarts it. If you use CTRL-S, stopping the flow of text, and so on, you must remember to type CTRL-Q or the computer will not respond. more is a program that displays only one screen of information at a time; it waits for you to tell it to continue. Type more followed by a filename. more practice The computer will display one screen of text and then wait for you to press the space bar before it displays the next page of text, until you reach the end of the file. Pressing the "?" character will show help for more. A utility of greater power called most is available on many systems; it allows reverse scrolling of files and other enhancements. It is invoked the same way as more.

Listing Files
The ls command will list the files in the current directory that do not begin with a period. Below is a list of options you can tack on to ls:
ls -a lists all the contents of the current directory, including files with initial periods, which are not usually listed. ls -l format, ls -s current lists the contents of the current directory in long including file permissions, size, and date information. lists contents and file sizes in kilobytes of the directory.

If you have many files, your directory list might be longer than one screen. You can use the programs more or most with the "|" (vertical bar or pipe) symbol to pipe the directory list generated as output by the ls command into the more program. more or most will display the output from ls one page at a time.

ls | more

Copying Files
To make a copy of a file, use the cp (copy) command. cp filename newfilename where filename is the file you wish to copy and newfilename is the file you are creating. cp practice sample (make a copy of "practice" called "sample") ls
practice sample

The example created a new file called sample that has the same contents as practice. If sample already exists, the cp command will overwrite the previous contents. New accounts are often set up so that cp will prompt for confirmation before it overwrites an existing file. If your account is not set up in this manner, use the -i option (cp -i) to get the confirmation prompt.

Renaming Files
To rename one of your files, use the mv (move) command. mv oldfilename newfilename

where oldfilename is the original filename and newfilename is the new filename. For instance, to rename sample as workfile type: mv sample workfile ls
practice workfile

This moves the contents of sample into the new file workfile. (Note: Moving a file into an existing file overwrites the data in the existing file.) New accounts are often set up so that mv will prompt for confirmation before doing this. If your account is not set up in this manner, use the -i option (mv -i) to get the confirmation prompt.

Deleting Files
To delete files, use the rm (remove) command. For instance, to delete workfile, type: rm workfile ls
practice

Important: rm can be very dangerous. Once a file has been removed you cannot get it back, except, possibly, from system backups (which may or may not contain the file). It may take the system administrators several days to to recover your deleted file, so use a great deal of caution when deleting files. New accounts are often set up so that rm will prompt for confirmation. If your account is not set up in this manner, use the -i option to get the confirmation prompt.

Creating Links Between Files


You can refer to one particular file by different names in different directories. The ln command creates a link, which "points" to the file. Note that links are simply alternative names for a single file; ln does not rename the file (as does mv) nor does it make a copy of the file (as does cp). It allows you to access the file from multiple directories. Since only one copy of the file actually exists, any changes that you make through one of its links will be reflected when you access it through another of its links, yet if you delete the link, you do not delete what it points to. Links are useful for cross-referencing files. If you know that you will need to access a file from different directories, creating links is a better alternative to making a copy of the file for each directory (and then having to alter each one every time a change is made to the original). It is also more convenient than having to use the file's full pathname every time you need to access it. Another use for linking a file is to allow another user access to that particular file without also allowing entry into the directory that actually contains the file. The kind of link you will want to create is called a symbolic link. A symbolic link contains the pathname of the file you wish to create a link to. Symbolic links can tie into any file in the file structure; they are not limited to files within a file system. Symbolic links may also refer to directories as well as individual files. To create a symbolic link to a file within the same directory, type:

ln -s originalFile linkName where originalFile is the file that you want to link to and linkName is the link to that file. To create a link in a directory other than that of the original file, type: ln -s originalFile differentDirectoryName/linkName If you create a link within the same directory as the original file, you cannot give it the same name as the original file. There is no restriction on a file's additional names outside of its own directory. Links do not change anything about a file, no matter what the link is named. If someone makes a link to one of your files, and you then delete that file, that link will no longer point to anything and may cause problems for the other user.

Printing Files
To print a file, use the lpr command: lpr filename or lpr [-Pprintername] filename (for laser printers only) To get a list of the printers available to your machine, type: lprloc lprloc lists all of the printers that your system knows about, by name, along with their type and location. To get some status information on the printers, use the command lpstat -p. NOTE: Line printers are used for text-only files. Laser printers are needed to handle graphics or PostScript files. PostScript is a page-description language developed by Adobe Systems, Inc. and was specially designed for creating graphics and typography on a printed page. The option flag -Pprintername specifies which laser printer to use and is optional (as indicated by the brackets). When no printer is given, the print command uses the system default printer. However, on some systems such as Owlnet, you must always specify a laser printer with the -P flag. For more information on printing commands, use the man command to consult the manual pages on lpq, lpr, and lprm.

Directories
About UNIX Directories

UNIX directories are similar to regular files; they both have names and both contain information. Directories, however, contain other files and directories. Many of the same rules and commands that apply to files also apply to directories. All files and directories in the UNIX system are stored in a hierarchical tree structure. Envision it as an upside-down tree, as in the figure below.

FIGURE 3. UNIX Directory Structure At the top of the tree is the root directory. Its directory name is simply / (a slash character). Below the root directory is a set of major subdirectories that usually include bin, dev, etc, lib, pub, tmp, and usr. For example, the /bin directory is a subdirectory, or "child," of / (the root directory). The root directory, in this case, is also the parent directory of the bin directory. Each path leading down, away from the root, ends in a file or directory. Other paths can branch out from directories, but not from files. Many directories on a UNIX system have traditional names and traditional contents. For example, directories named bin contain binary files, which are the executable command and application files. A lib directory contains library files, which are often collections of routines that can be included in programs by a compiler. dev contains device files, which are the software components of terminals, printers, disks, etc. tmp directories are for temporary storage, such as when a program creates a file for something and then deletes it when it is done. The etc directory is used for miscellaneous administrative files and commands. pub is for public files that anyone can use, and usr has traditionally been reserved for user directories, but on large systems it usually contains other bin, tmp, and lib directories. Your home directory is the directory that you start out from when you first login. It is the top level directory of your account. Your home directory name is almost always the same as your userid. Every directory and file on the system has a path by which it is accessed, starting from the root directory. The path to the directory is called its pathname. You can refer to any point in the directory hierarchy in two different ways: using its full (or absolute) pathname or its relative pathname. The full pathname traces the absolute position of a file or directory back to the root directory, using slashes (/) to connect every point in the path. For example, in the figure above, the full pathname of file2 would be /usr/bin/file2. Relative pathnames begin with the current directory (also called the working directory, the one you are in). If /usr were your current directory, then the relative pathname for file2 would be bin/file2. If you are using C shell, TC shell, or the Bourne-Again shell, UNIX provides some abbreviations for a few special directories. The character "~" (tilde) refers to your home directory. The home directory of any user (including you, if you want) can be abbreviated

from /parent-directories/userid to ~userid. Likewise, you can abbreviate /parentdirectories/youruserid/file to ~/file. The current directory has the abbreviation . (period). The parent of the current working directory uses .. (two consecutive periods) as its abbreviation.

Displaying Directories
When you initially log in, the UNIX system places you in your home directory. The pwd command will display the full pathname of the current directory you are in. pwd /home/userid By typing the ls -a command, you can see every file and directory in the current directory, regardless of whether it is your home directory. To display the contents of your home directory when it is not your current directory, enter the ls command followed by the full pathname of your home directory. ls /home/userid If you are using a shell other than the Bourne shell, instead of typing the full pathname for your directory, you can also use the tilde symbol with the ls command to display the contents of your home directory. ls ~ To help you distinguish between files and directories in a listing, the ls command has a -F option, which appends a distinguishing mark to the entry name showing the kind of data it contains: no mark for regular files; "/" for directories; "@" for links; "*" for executable programs.

Changing Directories
To change your current directory to another directory in the directory tree, use the cd command. For example, to move from your home directory to your projects directory, type: cd projects (relative pathname from home directory) or, cd ~/projects (full pathname using ~) or, cd /home/userid/projects (full pathname) Using pwd will show you your new current directory. pwd
home/userid/projects

To get back to the parent directory of projects, you can use the special ".." directory abbreviation. cd .. pwd
/home/userid

If you get lost, issuing the cd command without any arguments will place you in your home directory. It is equivalent to cd ~.

Moving Files Between Directories


You can move a file into another directory using the following syntax for the mv command: mv source-filename destination-directory For example, mv sample.txt ~/projects moves the file sample.txt into the projects directory. Since the mv command is capable of overwriting files, it would be prudent to use the -i option (confirmation prompt). You can also move a file into a another directory and rename it at the same time by merely specifying the new name after the directory path, as follows: mv sample.txt ~/projects/newsample.txt

Copying Files to Other Directories


As with the mv command, you can copy files to other directories: cp sample.txt ~/projects As with mv, the new file will have the same name as the old one unless you change it while copying it. cp sample.txt ~/projects/newsample.txt

Renaming Directories
You can rename an existing directory with the mv command: mv oldDirectory newDirectory

The new directory name must not exist before you use the command. The new directory need not be in the current directory. You can move a directory anywhere within a file system.

Removing Directories
To remove a directory, first be sure that you are in the parent of that directory. Then use the command rmdir along with the directory's name. You cannot remove a directory with rmdir unless all the files and subdirectories contained in it have been erased. This prevents you from accidentally erasing important subdirectories. You could erase all the files in a directory by first going to that directory (use cd) and then using rm to remove all the files in that directory. The quickest way to remove a directory and all of its files and subdirectories (and their contents) is to use the rm -r command along with the directory's name. For example, to empty and remove your projects directory (assuming that you are in that directory), type: cd .. (move to that directory's parent) rm -r projects (remove the directory and its contents)

File and Directory Permissions


It is important to protect your UNIX files against accidental (or intentional) removal or alteration by yourself or other users. The UNIX operating system maintains information, known as permissions, for every file and directory on the system. This section describes how to inspect and change these permissions. UNIX was designed and implemented by computer scientists working on operating system research. Many of the fundamentals of UNIX reflect this origin in academia. A low concern for security is one of the hallmarks of UNIX operating systems. Therefore, unless you act to restrict access to your files, chances are high that other users can read them. Every file or directory in a UNIX file system has three types of permissions (or protections) that define whether certain actions can be carried out. The permissions are: read ( r ) A user who has read permission for a file may look at its contents or make a copy of it. For a directory, read permission enables a user to find out what files are in that directory. write ( w ) A user who has write permission for a file can alter or remove the contents of that file. For a directory, the user can create and delete files in that directory.

execute ( x ) A user who has execute permission for a file can cause the contents of that file to be executed (provided that it is executable). For a directory, execute permission allows a user to change to that directory. For each file and directory, the read, write, and execute permissions may be set separately for each of the following classes of users: User ( u ) The user who owns the file or directory. Group ( g ) Several users purposely lumped together so that they can share access to each other's files. Others ( o ) The remainder of the authorized users of the system.

The primary command that displays information about files and directories is ls. The -l option will display the information in a long format. You can get information about a single UNIX file by using ls -l filename. Each file or subdirectory entry in a directory listing obtained with the -l option consists of seven fields: permission mode, link count, owner name, group name, file size in bytes, time of last modification, and the filename (the group name appears only if the "g" flag is also specified, as in ls -lg). The first 10 characters make up the mode field. If the first character is a "d" then the item listed is a directory; if it is a "-" then the item is a file; if it is an "l" then it is a link to another file. Characters 2 through 4 refer to the owner's permissions, characters 5 through 7 to the group's permissions (groups are defined by the system administrator), and the last three to the general public's permissions. (You can type id to verify your userid and group membership.) If a particular permission is set, the appropriate letter appears in the corresponding position; otherwise, a dash indicates that the permission is not given. The second field in the output from ls -l is the number of links to the file. In most cases it is one, but other users may make links to your files, thus increasing the link count. A special warning to people using links to other people's files: your "copies" of their files can be counted against them by the file quota system available on certain UNIX variants. The third field gives the userid of the owner of the file. The group name follows in the fourth field (if the -g option is used in conjunction with -l). The next two fields give the size of the file (in bytes) and the date and time at which the file was last modified. The last field gives the name of the file.

ls -l myfile
-rw-r--r-- 1 owner 588 Jul 15 14:39 myfile

A file's owner can change any or all of the permissions with the chmod (change mode) command. The chmod command allows you to dictate the type of access permission that you want each file to have. In the previous example the current permissions for myfile are read for everybody, write for the owner, and execute by no one. The arguments supplied to chmod are a symbolic specification of the changes required, followed by one or more filenames. The specification consists of whose permissions are to be changed: u for user (owner), g for group, o for others, or some combination thereof (a (all) has the same effect as ugo), how they are to be changed (+ adds a permission, removes a permission, and = sets the specified permissions, removing the other ones) and which permission to add or remove (r for read, w for write, and x for execute). For example, to remove all the permissions from myfile:

chmod a-rwx myfile ls -l myfile

---------- 1 owner 588 Jul 15 14:41 myfile

(Note: chmod a= myfile achieves the same effect.) To allow read and write permissions for all users:

chmod ugo+rw myfile ls -l myfile


-rw-rw-rw- 1 owner 588 Jul 15 14:42 myfile

To remove write permission for your groups and other users:

chmod go-w myfile ls -l myfile

-rw-r--r-- 1 owner 588 Jul 15 14:42 myfile

Finally, to allow only read permission to all users:

chmod a=r myfile ls -l myfile


-r--r--r-- 1 owner 58 Jul 15 14:43 myfile

Now the file is protected by allowing only read access; it cannot be written to or executed by anyone, including you. Protecting a file against writing by its owner is a safeguard against accidental overwriting, although not against accidental deletion. chmod will also accept a permission setting expressed as a 3-digit octal number. To determine this octal number, you first write a 1 if the permission is to be set and a 0 otherwise. This produces a binary number which can be converted into octal by grouping the digits in threes and replacing each group by the corresponding octal digit according to the table below. TABLE 2. Symbolic to Octal Conversions
SYMBOLIC ----x -w-wx r-r-x rwrwx BINARY 000 001 010 011 100 101 110 111 OCTAL 0 1 2 3 4 5 6 7

Thus, if the setting you want is rw-r--r--, determine the octal number with the following method:

This shows that the octal equivalent of rw-r--r-- is 644. The following example illustrates that the permissions for myfile have been reset to the values with which we began.

chmod 644 myfile ls -l myfile


-rw-r--r-- 1 owner 588 Jul 15 14:44 myfile

To change the permissions back to read only, you can execute chmod as follows:

chmod 444 myfile ls -l myfile


-r--r--r-- 1 owner 588 Jul 15 14:45 myfile

As with files, directories may also have permissions assigned. When listing directories, you may use the -d option to keep from descending into the directories you list. Otherwise, the contents of the directories will be displayed as well as their names. Below is an example of permissions assigned to a directory:

ls -lgd home

drwxrwxr-x 1 owner masc223 588 Jul 15 9:45 home

The directory home and the files and directories under it may be read and executed by anyone, but written to only by the owner and users in the masc223 group. Assuming you are the owner of this directory, you may decide to change the permission to allow only yourself and the masc223 group to read and execute files in the home directory. You would set the permissions accordingly:

chmod o-rx home ls -lgd home


drwxrwx--- 1 owner masc223 588Jul 15 9:46 home

You may decide that only you should be able to alter the contents of the directory. You must remove the write permission for the group.

chmod 750 home ls -lgd home

drwxr-x--- 1 owner masc223 588 Jul 15 9:48 home

An alternative to the previous command is chmod g-w. When you create a file the system gives it a default set of permissions. These are controlled by the system administrator and will vary from installation to installation. If you would like to change the default which is in effect for you, choose your own with the umask command. Note that the permission specified by the umask setting will be applied to the file, unlike that specified in the chmod command, which normally only adds or deletes (few people use the = operator to chmod).

First, issue the command without arguments to cause the current settings to be echoed as an octal number:

umask
022

If you convert these digits to binary, you will obtain a bit pattern of 1's and 0's. A 1 indicates that the corresponding permission is to be turned off, a 0, that it is to be turned on. (Notice that the bit patterns for chmod and umask are reversed.) Hence, the mask output above is 000010010, which produces a permission setting of rwxr-xr-x (i.e., write permission is turned off for group and other). Suppose you decide that the default setting you prefer is rwxr-x---. This corresponds to the masking bit pattern 000010111, so the required mask is 027:

umask 27 Now, if you create a new file during this session, the permissions assigned to the file will be the ones allowed by the mask value.

Wildcard Characters
Using wildcard characters that allow you to copy, list, move, remove, etc. items with similar names is a great help in manipulating files and directories. 1. The symbol ? will match any single character in that position in the file name. 2. The symbol * will match zero or more characters in the name. 3. Characters enclosed in brackets [and] will match any one of the given characters in the given position in the name. A consecutive sequence of characters can be designated by [char char]. Examples of each follow: 1. ?ab2 would match a name that starts with any single character and ends with ab2. ?ab? would match all names that begin and end with any character and have ab in between. 2. ab* would match all names that start with ab, including ab itself. a*b would match all names that start with a and end with b, including ab. 3. s[aqz] would match sa, sq, and sz.

s[2-7] would match s2, s3, s4, s5, s6 and s7. These wildcard symbols help in dealing with groups of files, but you should remember that the instruction: rm * would erase all files in your current directory (although by default, you would be prompted to okay each deletion). The wildcard * should be used carefully.

Processes
Every command or program running under UNIX is called a process. A sequence of related processes is called a job. Your applications and even your shell itself are processes. The windowing system is also a process, or a collection of processes. The UNIX kernel manages the processes on the system, usually without distinguishing among them. UNIX is a multi-tasking system---it allows you to continue to work in the foreground while running one or more jobs in the background. It also runs the processes of many users simultaneously. You could even log off and come back later if the background jobs do not require interaction with you.

Viewing Your Processes


The command ps will show you the status of your processes. ps
PID 4804 1352 3874 3875 3879 3880 3892 TT p3 p3 p7 p7 p7 p7 p9 STAT TIME COMMAND S 0:00 -sh (csh) R 0:00 ps IW 0:25 xclock -g 90x90-0+0 S 0:48 xbiff -g 90x90-95+0 S 0:10 twm IW 0:00 -bin/csh (csh) IW 0:24 /usr/local/bin/elm

ps displays the process ID, under PID; the control terminal (if any), under TT; the state of the process, under STAT; the cpu time used by the process so far (including both user and system time), under TIME; and finally, an indication of the COMMAND that is running. The state of the process is indicated by a sequence of letters. The man pages for ps explain what the letters mean if you want to know. For most purposes, you won't really need to know what the letters mean.

Running Background Jobs

Putting a program into an unattended state where it continues to execute is referred to as putting it (the process or job) into the background. (Running a program on one machine and displaying its output on another via a windowing system like X is not considered backgrounding the job.) Adding an & (ampersand) at the end of the command line instructs UNIX to run the job in the background.

jobname & The response you receive will be something like this:
[1] 5432

This particular response means that you have one job running in the background (and its job number is 1), and its process identification number (PID) is 5432. You will need to know the PID if you want to stop the job. This is known as killing a job. To kill the job in the above example, you would type: kill 5432 In the C shell, the job number can be used to control which jobs run in background or foreground. The job number is used when switching a job that is processing in the foreground to the background, and one that is processing in the background to the foreground. To do the former, first press CTRL-Z to suspend the job. Then type: bg %jobNumber To switch the job to the foreground, simply type: fg %jobNumber If you have forgotten the job number, type the command jobs to see a list of the jobs that are running in the background at the moment. Note: The rules imposed by system administrators about where and how to run background jobs varies from network to network and changes over time. It is important to stay current with the background job policy of your network.

Process Scheduling Priority


The nice command is used to set the processing priority of a command. The priority of a process determines how much attention the system will devote to completing that job. The higher the priority, the more attention a job gets, which implies that it will take less

time to complete than the same job run at a lower priority. There are two versions of nice. In the C shell, the syntax is: nice -priorityNumber command argument In the Bourne shell, the syntax is:

nice +priorityNumber command argument The available priority numbers for users ranges from 1 to 19 with 19 being the lowest priority. In other words, the higher the nice value, the lower the processing priority. (Note: It is important to check the network policy for the required nice value for background jobs on your system; they are usually required to be niced and your job may be downgraded in priority if it was niced at the wrong value.) Set your command at the required nice value or higher. If you do not include a number argument, the value will default to 4 for the C shell and 10 for the Bourne shell. For example, if you wanted to run a long non-interactive job, and you didn't have to have the results of this job right away, you should run it in the background and set a high nice value. Using the C shell, you would type:

nice -19 jobname &

Remote Login
Sometimes, while you are logged into one workstation, you will find that you would like to be logged in to another workstation, file server, or other UNIX system. The command rlogin allows you to do so provided that you have an account on the other system. Type: rlogin newSystem You may then have to supply your password. You should also get the messages about logging in that are used on newSystem. If your userid is different on newSystem you will have to use the form: rlogin newSystem -l userid

Troubleshooting

Logging In
Problem: Nothing happens when you type CTRL-C to begin your session. Try typing CTRL-C several times in a row at the prompt. If that doesn't work, type CTRL-\. It's a more powerful interrupt. Problem: The system prints "login incorrect." Check to make sure that you are typing your userid and password exactly as they appear on your information sheet (make sure you're using the proper case for all characters). If you still cannot log in, go to the Consulting Center in 103 Mudd Lab and ask for help. Problem: The computer types everything in upper-case with slashes in it. SAMPLE OF WHAT PROBLEM LOOKS LIKE Your userid was entered in uppercase letters, so the system thinks that your terminal can only understand uppercase letters. You need to type logout and then login again making sure that you enter your userid in lowercase letters only. (If the screen displays uppercase as you type your userid, you may have to turn the CAPS key "off" by pressing it once and try logging in once more.)

Logging Out
If you experience difficulty logging out, check to see if you are having one of the following problems. Do not turn off the workstation or terminal. This will not disconnect you from UNIX. Problem: The system replies "There are stopped jobs" when you try to log out. Type jobs to see what they are, then type kill %% to terminate all stopped background jobs. After that, try logging out again. Problem: The system replies, "Not in login shell." First, type exit, press RETURN, and then type logout at the prompt, if necessary. Problem: Nothing seems to work and you can't log out. You might be stuck in a program or shell other than the login shell. Press RETURN to clear any previous commands; then try typing CTRL-C, q, :q, :q!, exit, CTRL-D, CTRLQ, or CTRL-Z to get back into the login shell. Then try logout again. The following sequence might also work if your terminal is NOT connected directly to your real host machine. Press RETURN, then type "~." followed by RETURN.

Additional Resources

You now have enough information to get started using UNIX. To learn more about UNIX and specific applications, you can refer to a number of resources. You can use the man command to get on-line help. This is the quickest and easiest way to get help during a UNIX session. Virtually every UNIX operation and command has an entry. UNIX documentation written by the vendor for their workstations is available in the document racks of Information Systems maintained networks. Below are some of the UNIX-related documents.

Introduction to the X Window System Customizing the X Window System Introduction to the vi Editor Introduction to the aXe Editor Introduction to GNU Emacs Compilers, Make, and Debuggers

Basic UNIX commands


Note: not all of these are actually part of UNIX itself, and you may not find them on all UNIX machines. But they can all be used on turing in essentially the same way, by typing the command and hitting return. Note that some of these commands are different on non-Solaris machines - see SunOS differences. If you've made a typo, the easiest thing to do is hit CTRL-u to cancel the whole line. But you can also edit the command line (see the guide to More UNIX). UNIX is case-sensitive.

Files

ls --- lists your files ls -l --- lists your files in 'long format', which contains lots of useful information, e.g. the exact size of the file, who owns the file and who has the right to look at it, and when it was last modified. ls -a --- lists all files, including the ones whose filenames begin in a dot, which you do not always want to see. There are many more options, for example to list files by size, by date, recursively etc. more filename --- shows the first part of a file, just as much as will fit on one screen. Just hit the space bar to see more or q to quit. You can use /pattern to search for a pattern. emacs filename --- is an editor that lets you create and edit a file. See the emacs page.

mv filename1 filename2 --- moves a file (i.e. gives it a different name, or moves it into a different directory (see below) cp filename1 filename2 --- copies a file rm filename --- removes a file. It is wise to use the option rm -i, which will ask you for confirmation before actually deleting anything. You can make this your default by making an alias in your .cshrc file. diff filename1 filename2 --- compares files, and shows where they differ wc filename --- tells you how many lines, words, and characters there are in a file chmod options filename --- lets you change the read, write, and execute permissions on your files. The default is that only you can look at them and change them, but you may sometimes want to change these permissions. For example, chmod o+r filename will make the file readable for everyone, and chmod o-r filename will make it unreadable for others again. Note that for someone to be able to actually look at the file the directories it is in need to be at least executable. See help protection for more details. File Compression o gzip filename --- compresses files, so that they take up much less space. Usually text files compress to about half their original size, but it depends very much on the size of the file and the nature of the contents. There are other tools for this purpose, too (e.g. compress), but gzip usually gives the highest compression rate. Gzip produces files with the ending '.gz' appended to the original filename. o gunzip filename --- uncompresses files compressed by gzip. o gzcat filename --- lets you look at a gzipped file without actually having to gunzip it (same as gunzip -c). You can even print it directly, using gzcat filename | lpr printing o lpr filename --- print. Use the -P option to specify the printer name if you want to use a printer other than your default printer. For example, if you want to print double-sided, use 'lpr -Pvalkyr-d', or if you're at CSLI, you may want to use 'lpr -Pcord115-d'. See 'help printers' for more information about printers and their locations. o lpq --- check out the printer queue, e.g. to get the number needed for removal, or to see how many other files will be printed before yours will come out o lprm jobnumber --- remove something from the printer queue. You can find the job number by using lpq. Theoretically you also have to specify a printer name, but this isn't necessary as long as you use your default printer in the department. o genscript --- converts plain text files into postscript for printing, and gives you some options for formatting. Consider making an alias like alias ecop 'genscript -2 -r \!* | lpr -h -Pvalkyr' to print two pages on one piece of paper. o dvips filename --- print .dvi files (i.e. files produced by LaTeX). You can use dviselect to print only selected pages. See the LaTeX page for more information about how to save paper when printing drafts.

Directories
Directories, like folders on a Macintosh, are used to group files together in a hierarchical structure. mkdir dirname --- make a new directory cd dirname --- change directory. You basically 'go' to another directory, and you will see the files in that directory when you do 'ls'. You always start out in your 'home directory', and you can get back there by typing 'cd' without arguments. 'cd ..' will get you one level up from your current position. You don't have to walk along step by step - you can make big leaps or avoid walking around by specifying pathnames. pwd --- tells you where you currently are.

Finding things

ff --- find files anywhere on the system. This can be extremely useful if you've forgotten in which directory you put a file, but do remember the name. In fact, if you use ff -p you don't even need the full name, just the beginning. This can also be useful for finding other things on the system, e.g. documentation. grep string filename(s) --- looks for the string in the files. This can be useful a lot of purposes, e.g. finding the right file among many, figuring out which is the right version of something, and even doing serious corpus work. grep comes in several varieties (grep, egrep, and fgrep) and has a lot of very flexible options. Check out the man pages if this sounds good to you.

About other people

w --- tells you who's logged in, and what they're doing. Especially useful: the 'idle' part. This allows you to see whether they're actually sitting there typing away at their keyboards right at the moment. who --- tells you who's logged on, and where they're coming from. Useful if you're looking for someone who's actually physically in the same building as you, or in some other particular location. finger username --- gives you lots of information about that user, e.g. when they last read their mail and whether they're logged in. Often people put other practical information, such as phone numbers and addresses, in a file called .plan. This information is also displayed by 'finger'. last -1 username --- tells you when the user last logged on and off and from where. Without any options, last will give you a list of everyone's logins. talk username --- lets you have a (typed) conversation with another user write username --- lets you exchange one-line messages with another user elm --- lets you send e-mail messages to people around the world (and, of course, read them). It's not the only mailer you can use, but the one we recommend. See the elm page, and find out about the departmental mailing lists (which you can also find in /user/linguistics/helpfile).

About your (electronic) self

whoami --- returns your username. Sounds useless, but isn't. You may need to find out who it is who forgot to log out somewhere, and make sure *you* have logged out. finger & .plan files of course you can finger yourself, too. That can be useful e.g. as a quick check whether you got new mail. Try to create a useful .plan file soon. Look at other people's .plan files for ideas. The file needs to be readable for everyone in order to be visible through 'finger'. Do 'chmod a+r .plan' if necessary. You should realize that this information is accessible from anywhere in the world, not just to other people on turing. passwd --- lets you change your password, which you should do regularly (at least once a year). See the LRB guide and/or look at help password. ps -u yourusername --- lists your processes. Contains lots of information about them, including the process ID, which you need if you have to kill a process. Normally, when you have been kicked out of a dialin session or have otherwise managed to get yourself disconnected abruptly, this list will contain the processes you need to kill. Those may include the shell (tcsh or whatever you're using), and anything you were running, for example emacs or elm. Be careful not to kill your current shell - the one with the number closer to the one of the ps command you're currently running. But if it happens, don't panic. Just try again :) If you're using an X-display you may have to kill some X processes before you can start them again. These will show only when you use ps -efl, because they're root processes. kill PID --- kills (ends) the processes with the ID you gave. This works only for your own processes, of course. Get the ID by using ps. If the process doesn't 'die' properly, use the option -9. But attempt without that option first, because it doesn't give the process a chance to finish possibly important business before dying. You may need to kill processes for example if your modem connection was interrupted and you didn't get logged out properly, which sometimes happens. quota -v --- show what your disk quota is (i.e. how much space you have to store files), how much you're actually using, and in case you've exceeded your quota (which you'll be given an automatic warning about by the system) how much time you have left to sort them out (by deleting or gzipping some, or moving them to your own computer). du filename --- shows the disk usage of the files and directories in filename (without argument the current directory is used). du -s gives only a total. last yourusername --- lists your last logins. Can be a useful memory aid for when you were where, how long you've been working for, and keeping track of your phonebill if you're making a non-local phonecall for dialling in.

Connecting to the outside world

nn --- allows you to read news. It will first let you read the news local to turing, and then the remote news. If you want to read only the local or remote news, you

can use nnl or nnr, respectively. To learn more about nn type nn, then \tty{:man}, then \tty{=.*}, then \tty{Z}, then hit the space bar to step through the manual. Or look at the man page. Or check out the hypertext nn FAQ - probably the easiest and most fun way to go. rlogin hostname --- lets you connect to a remote host telnet hostname --- also lets you connect to a remote host. Use rlogin whenever possible. ftp hostname --- lets you download files from a remote host which is set up as an ftp-server. This is a common method for exchanging academic papers and drafts. If you need to make a paper of yours available in this way, you can (temporarily) put a copy in /user/ftp/pub/TMP. For more permanent solutions, ask Emma. The most important commands within ftp are get for getting files from the remote machine, and put for putting them there (mget and mput let you specify more than one file at once). Sounds straightforward, but be sure not to confuse the two, especially when your physical location doesn't correspond to the direction of the ftp connection you're making. ftp just overwrites files with the same filename. If you're transferring anything other than ASCII text, use binary mode. lynx --- lets you browse the web from an ordinary terminal. Of course you can see only the text, not the pictures. You can type any URL as an argument to the G command. When you're doing this from any Stanford host you can leave out the .stanford.edu part of the URL when connecting to Stanford URLs. Type H at any time to learn more about lynx, and Q to exit.

Miscellaneous tools

webster word --- looks up the word in an electronic version of Webster's dictionary and returns the definition(s) date --- shows the current date and time. cal --- shows a calendar of the current month. Use e.g., 'cal 10 1995' to get that for October 95, or 'cal 1995' to get the whole year.

You can find out more about these commands by looking up their manpages: man commandname --- shows you the manual page for the command

Some Useful UNIX Commands


What follows are some excerpts from the manual pages; for complete descriptions, use man command Square brackets [ ... ] denote optional arguments to the command. cd [ directory ]

directory becomes the new working directory. The process must have execute (search) permission in directory. If cd is used without arguments, it returns you to your login directory. cp file1 file2 cp copies the contents of filename1 onto filename2. The mode and owner of filename2 are preserved if it already existed; the mode of the source file is used otherwise. If filename1 is a symbolic link, or a duplicate hard link, the contents of the file that the link refers to are copied; links are not preserved. diff [ options ] filename1 filename2 diff is a differential file comparator. When run on regular files, and when comparing text files that differ during directory comparison (see the notes below on comparing directories), diff tells what lines must be changed in the files to bring them into agreement. Except in rare circumstances, diff finds a smallest sufficient set of differences. If neither filename1 nor filename2 is a directory, either may be given as `-', in which case the standard input is used. If filename1 is a directory, a file in that directory whose filename is the same as the filename of filename2 is used (and vice versa). du [ -s ] [ -a ] [ filename ... ] du gives the number of kilobytes contained in all files and, recursively, directories within each specified directory or file filename. If filename is missing, `.' (the current directory) is used. elm Elm is an interactive screen-oriented mailer program that supersedes mail and mailx. emacs [ filename ] MicroEMACS is a tool for creating and changing documents, programs, and other text files. It is both relatively easy for the novice to use, but also very powerful in the hands of an expert. MicroEMACS can be extensively customized for the needs of the individual user. finger [ options ] [ name ] By default, finger displays information about each logged-in user, including his or her: login name, full name, terminal name (prepended with a `*' if writepermission is denied), idle time, login time, and location (comment field in /etc/ttytab for users logged in locally, hostname for users logged in remotely) if known. ftp [ host ] ftp is the user interface to the ARPANET standard File Transfer Protocol (FTP). ftp transfers files to and from a remote network site. handout Handout allows access to a handout in the category of your choice. Handout provides a menu of current handouts and interactively allows viewing, copying, and printing of handouts in the specified categories. lpq [ -Pprinter ] lpq displays the contents of a printer queue. It reports the status of jobs specified by job#, or all jobs owned by the user specified by username. lpq reports on all jobs in the default printer queue when invoked with no arguments.

lpr [ -Pprinter ] filename lpr creates a printer job in a spooling area for subsequent printing as facilities become available. Each printer job consists of a control file and one or more data files. The data files are copies of (or, with -s , symbolic links to) each filename you specify. The spool area is managed by the line printer daemon, lpd. Jobs that specify a printer on a remote machine are forwarded by lpd. lprm [ -Pprinter ] [ - ] [ job# ] [ username ] lprm removes a job or jobs from a printer's spooling queue. Since the spool directory is protected from users, using lprm is normally the only method by which a user can remove a job. ls [ options ] [ name ] For each filename which is a directory, ls lists the contents of the directory; for each filename which is a file, ls repeats its name and any other information requested. By default, the output is sorted alphabetically. When no argument is given, the current directory is listed. When several arguments are given, the arguments are first sorted appropriately, but file arguments are processed before directories and their contents. mail [ options ] [ recipient ] mail is a comfortable, flexible, interactive program for composing, sending and receiving electronic messages. While reading messages, mail provides you with commands to browse, display, save, delete, and respond to messages. While sending mail, mail allows editing and reviewing of messages being composed, and the inclusion of text from files or other messages. man [ options ] name man displays information from the reference manuals. It can display complete manual pages that you select by title, or one-line summaries selected either by keyword (-k), or by the name of an associated file (-f). mkdir directory mkdir creates directories. Standard entries, `.', for the directory itself, and `..' for its parent, are made automatically. more file more is a filter that displays the contents of a text file on the terminal, one screenful at a time. It normally pauses after each screenful, and prints --More-- at the bottom of the screen. more provides a two-line overlap between screens for continuity. If more is reading from a file rather than a pipe, the percentage of characters displayed so far is also shown. mv file1 file2 mv moves files and directories around in the file system. A side effect of mv is to rename a file or directory. paper [ user ] Paper displays paper usage information stored in the default paper quota file /usr/adm/pquota. Each user has an entry in the paper quota file on the home site of the user. passwd passwd changes (or installs) a password, login shell (-s option), or full name (-f option) associated with the user username (your own by default). chsh is

equivalent to passwd with the -s option, and chfn is equivalent to passwd with the -f option. ps [ options ] ps displays information about processes. Normally, only those processes that are running with your effective user ID and are attached to a controlling terminal (see termio(4)) are shown. Additional categories of processes can be added to the display using various options. In particular, the -a option allows you to include processes that are not owned by you (that do not have your user ID), and the -x option allows you to include processes without control terminals. When you specify both -a and -x, you get processes owned by anyone, with or without a control terminal. The -r option restricts the list of processes printed to "running" processes: runnable processes, those in page wait, or those in short-term noninterruptible waits. quota [ -v ] [ username ] quota displays users' disk usage and limits. Only the super-user may use the optional username argument to view the limits of users other than himself. rm file rm removes (directory entries for) one or more files. If an entry was the last link to the file, the contents of that file are lost. See ln(1V) for more information about multiple links to files. rmdir directory rmdir removes each named directory. rmdir only removes empty directories. sort [ options ] filename The sort program sorts and collates lines contained in the named files, and writes the result onto the standard output. If no filename argument is given, or if `-' appears as an argument, sort accepts input from the standard input. telnet [ host [ port ] ] telnet communicates with another host using the TELNET protocol. If telnet is invoked without arguments, it enters command mode, indicated by its prompt (telnet>). In this mode, it accepts and executes the commands listed below. If it is invoked with arguments, it performs an open command (see below) with those arguments. vi [ options ] [ filename ] vi (visual) is a display oriented text editor based on ex. ex and vi are, in fact, the same text editor; it is possible to get to the command mode of ex from within vi and vice-versa. who Used without arguments, who lists the login name, terminal name, and login time for each current user. who gets this information from the /etc/utmp file

Other useful UNIX commands


quota

All students are allocated a certain amount of disk space on the file system for their personal files, usually about 5 Megabyes (equivalent to 4 floppy disks worth). If you go over your quota, you are given 7 days to remove excess files. To check your current quota and how much of it you have used, type % quota -v

df
The df command reports on the space left on the file system. For example, to find out how much space is left on the fileserver, type % df .

du
The du command outputs the number of kilobyes used by each subdirectory. Useful if you have gone over quota and you want to find out which directory has the most files. In your home-directory, type % du

compress
This reduces the size of a file, thus freeing valuable disk space. For example, type % ls -l science.txt and note the size of the file. Then to compress science.txt, type % compress science.txt This will compress the file and place it in a file called science.txt.Z To see the change in size, type ls -l again. To uncomress the file, use the uncompress command. % uncompress science.txt.Z

gzip
This also compresses a file, and is more efficient than compress. For example, to zip science.txt, type

% gzip science.txt This will zip the file and place it in a file called science.txt.gz To unzip the file, use the gunzip command. % gunzip science.txt.gz

file
file classifies the named files according to the type of data they contain, for example ascii (text), pictures, compressed data, etc.. To report on all files in your home directory, type % file *

history
The C shell keeps an ordered list of all the commands that you have entered. Each command is given a number according to the order it was entered. % history (show command history list) If you are using the C shell, you can use the exclamation character (!) to recall commands easily. % !! (recall last command) % !-3 (recall third most recent command) % !5 (recall 5th command in list) % !grep (recall last command starting with grep) You can increase the size of the history buffer by typing % set history=100

4.1 Wildcards
The characters * and ?

The character * is called a wildcard, and will match against none or more character(s) in a file (or directory) name. For example, in your unixstuff directory, type % ls list* This will list all files in the current directory starting with list.... Try typing % ls *list This will list all files in the current directory ending with ....list The character ? will match exactly one character. So ls ?ouse will match files like house and mouse, but not grouse. Try typing % ls ?list

4.2 Filename conventions


We should note here that a directory is merely a special type of file. So the rules and conventions for naming files apply also to directories. In naming files, characters with special meanings such as / * & % , should be avoided. Also, avoid using spaces within names. The safest way to name a file is to use only alphanumeric characters, that is, letters and numbers, together with _ (underscore) and . (dot). File names conventionally start with a lower-case letter, and may end with a dot followed by a group of letters indicating the contents of the file. For example, all files consisting of C code may be named with the ending .c, for example, prog1.c . Then in order to list all files containing C code in your home directory, you need only type ls *.c in that directory. Beware: some applications give the same name to all the output files they generate. For example, some compilers, unless given the appropriate option, produce compiled files named a.out. Should you forget to use that option, you are advised to rename the compiled file immediately, otherwise the next such file will overwrite it and it will be lost.

4.3 Getting Help


On-line Manuals

There are on-line manuals which gives information about most commands. The manual pages tell you which options a particular command can take, and how each option modifies the behaviour of the command. Type man command to read the manual page for a particular command. For example, to find out more about the wc (word count) command, type % man wc Alternatively % whatis wc gives a one-line description of the command, but omits any information about options etc.

Apropos
When you are not sure of the exact name of a command, % apropos keyword will give you the commands with keyword in their manual page header. For example, try typing % apropos copy

Summary
* ? man command whatis command apropos keyword

match any number of characters match one character read the online manual page for a command brief description of a command match commands with keyword in their man pages

5.1 File system security (access rights)


In your unixstuff directory, type % ls -l (l for long listing!)

You will see that you now get lots of details about the contents of your directory, similar to the example below.

Each file (and directory) has associated access rights, which may be found by typing ls -l. Also, ls -lg gives additional information as to which group owns the file (beng95 in the following example):

-rwxrw-r-- 1 ee51ab beng95 2450 Sept29 11:52 file1


In the left-hand column is a 10 symbol string consisting of the symbols d, r, w, x, -, and, occasionally, s or S. If d is present, it will be at the left hand end of the string, and indicates a directory: otherwise - will be the starting symbol of the string. The 9 remaining symbols indicate the permissions, or access rights, and are taken as three groups of 3.

The left group of 3 gives the file permissions for the user that owns the file (or directory) (ee51ab in the above example); the middle group gives the permissions for the group of people to whom the file (or directory) belongs (eebeng95 in the above example); the rightmost group gives the permissions for all others.

The symbols r, w, etc., have slightly different meanings depending on whether they refer to a simple file or to a directory.

Access rights on files.

r (or -), indicates read permission (or otherwise), that is, the presence or absence of permission to read and copy the file

w (or -), indicates write permission (or otherwise), that is, the permission (or otherwise) to change a file x (or -), indicates execution permission (or otherwise), that is, the permission to execute a file, where appropriate

Access rights on directories.


r allows users to list files in the directory; w means that users may delete files from the directory or move files into it; x means the right to access files in the directory. This implies that you may read files in the directory provided you have read permission on the individual files.

So, in order to read a file, you must have execute permission on the directory containing that file, and hence on any directory containing that directory as a subdirectory, and so on, up the tree.

Some examples
-rwxrwxrwx a file that everyone can read, write and execute (and delete). a file that only the owner can read and write - no-one else -rw------- can read or write and no-one has execution rights (e.g. your mailbox file).

5.2 Changing access rights


chmod (changing a file mode)
Only the owner of a file can use chmod to change the permissions of a file. The options of chmod are as follows Symbol u g o a r w user group other all read write (and delete) Meaning

x + -

execute (and access directory) add permission take away permission

For example, to remove read write and execute permissions on the file biglist for the group and others, type % chmod go-rwx biglist This will leave the other permissions unaffected. To give read and write permissions on the file biglist to all, % chmod a+rw biglist

Exercise 5a
Try changing access permissions on the file science.txt and on the directory backups Use ls -l to check that the permissions have changed.

5.3 Processes and Jobs


A process is an executing program identified by a unique PID (process identifier). To see information about your processes, with their associated PID and status, type % ps A process may be in the foreground, in the background, or be suspended. In general the shell does not return the UNIX prompt until the current process has finished executing. Some processes take a long time to run and hold up the terminal. Backgrounding a long process has the effect that the UNIX prompt is returned immediately, and other tasks can be carried out while the original process continues executing.

Running background processes


To background a process, type an & at the end of the command line. For example, the command sleep waits a given number of seconds before continuing. Type % sleep 10

This will wait 10 seconds before returning the command prompt %. Until the command prompt is returned, you can do nothing except wait. To run sleep in the background, type % sleep 10 &

[1] 6259
The & runs the job in the background and returns the prompt straight away, allowing you do run other programs while waiting for that one to finish. The first line in the above example is typed in by the user; the next line, indicating job number and PID, is returned by the machine. The user is be notified of a job number (numbered from 1) enclosed in square brackets, together with a PID and is notified when a background process is finished. Backgrounding is useful for jobs which will take a long time to complete.

Backgrounding a current foreground process


At the prompt, type % sleep 100 You can suspend the process running in the foreground by holding down the [control] key and typing [z] (written as ^Z) Then to put it in the background, type % bg Note: do not background programs that require user interaction e.g. pine

5.4 Listing suspended and background processes


When a process is running, backgrounded or suspended, it will be entered onto a list along with a job number. To examine this list, type % jobs An example of a job list could be

[1] Suspended sleep 100 [2] Running netscape [3] Running nedit
To restart (foreground) a suspended processes, type

% fg %jobnumber For example, to restart sleep 100, type % fg %1 Typing fg with no job number foregrounds the last suspended process.

5.5 Killing a process


kill (terminate or signal a process)
It is sometimes necessary to kill a process (for example, when an executing program is in an infinite loop) To kill a job running in the foreground, type ^C (control c). For example, run % sleep 100 ^C To kill a suspended or background process, type % kill %jobnumber For example, run % sleep 100 & % jobs If it is job number 4, type % kill %4 To check whether this has worked, examine the job list again to see if the process has been removed.

ps (process status)
Alternatively, processes can be killed by finding their process numbers (PIDs) and using kill PID_number % sleep 100 & % ps

PID TT S TIME 20077 pts/5 S 21563 pts/5 T 21873 pts/5 S

COMMAND 0:05 sleep 100 0:00 netscape 0:25 nedit

To kill off the process sleep 100, type % kill 20077 and then type ps again to see if it has been removed from the list. If a process refuses to be killed, uses the -9 option, i.e. type % kill -9 20077 Note: It is not possible to kill off other users' processes !!!

Summary
ls -lag chmod [options]

list access rights for all files

file change access rights for named file


run command in background kill the job running in the foreground suspend the job running in the foreground background the suspended job list current jobs foreground job number 1 kill job number 1 list current processes kill process number 26152

command
^C ^Z bg jobs fg %1 kill %1 ps kill 26152

&

8.1 UNIX Variables


Variables are a way of passing information from the shell to programs when you run them. Programs look "in the environment" for particular variables and if they are found

will use the values stored. Some are set by the system, others by you, yet others by the shell, or any program that loads another program. Standard UNIX variables are split into two categories, environment variables and shell variables. In broad terms, shell variables apply only to the current instance of the shell and are used to set short-term working conditions; environment variables have a farther reaching significance, and those set at login are valid for the duration of the session. By convention, environment variables have UPPER CASE and shell variables have lower case names.

8.2 Environment Variables


An example of an environment variable is the OSTYPE variable. The value of this is the current operating system you are using. Type % echo $OSTYPE More examples of environment variables are

USER (your login name) HOME (the path name of your home directory) HOST (the name of the computer you are using) ARCH (the architecture of the computers processor) DISPLAY (the name of the computer screen to display X windows) PRINTER (the default printer to send print jobs) PATH (the directories the shell should search to find a command)

Finding out the current values of these variables.


ENVIRONMENT variables are set using the setenv command, displayed using the printenv or env commands, and unset using the unsetenv command. To show all values of these variables, type % printenv | less

8.3 Shell Variables


An example of a shell variable is the history variable. The value of this is how many shell commands to save, allow the user to scroll back through all the commands they have previously entered. Type % echo $history More examples of shell variables are

cwd (your current working directory) home (the path name of your home directory) path (the directories the shell should search to find a command) prompt (the text string used to prompt for interactive commands shell your login shell)

Finding out the current values of these variables.


SHELL variables are both set and displayed using the set command. They can be unset by using the unset command. To show all values of these variables, type % set | less

So what is the difference between PATH and path ?


In general, environment and shell variables that have the same name (apart from the case) are distinct and independent, except for possibly having the same initial values. There are, however, exceptions. Each time the shell variables home, user and term are changed, the corresponding environment variables HOME, USER and TERM receive the same values. However, altering the environment variables has no effect on the corresponding shell variables. PATH and path specify directories to search for commands and programs. Both variables always represent the same directory list, and altering either automatically causes the other to be changed.

8.4 Using and setting variables


Each time you login to a UNIX host, the system looks in your home directory for initialisation files. Information in these files is used to set up your working environment. The C and TC shells uses two files called .login and .cshrc (note that both file names begin with a dot). At login the C shell first reads .cshrc followed by .login .login is to set conditions which will apply to the whole session and to perform actions that are relevant only at login. .cshrc is used to set conditions and perform actions specific to the shell and to each invocation of it.

The guidelines are to set ENVIRONMENT variables in the .login file and SHELL variables in the .cshrc file. WARNING: NEVER put commands that run graphical displays (e.g. a web browser) in your .cshrc or .login file.

8.5 Setting shell variables in the .cshrc file


For example, to change the number of shell commands saved in the history list, you need to set the shell variable history. It is set to 100 by default, but you can increase this if you wish. % set history = 200 Check this has worked by typing % echo $history However, this has only set the variable for the lifetime of the current shell. If you open a new xterm window, it will only have the default history value set. To PERMANENTLY set the value of history, you will need to add the set command to the .cshrc file. First open the .cshrc file in a text editor. An easy, user-friendly editor to use is nedit. % nedit ~/.cshrc Add the following line AFTER the list of other commands. set history = 200 Save the file and force the shell to reread its .cshrc file buy using the shell source command. % source .cshrc Check this has worked by typing % echo $history

8.6 Setting the path


When you type a command, your path (or PATH) variable defines in which directories the shell will look to find the command you typed. If the system returns a message saying "command: Command not found", this indicates that either the command doesn't exist at all on the system or it is simply not in your path.

For example, to run units, you either need to directly specify the units path (~/units174/bin/units), or you need to have the directory ~/units174/bin in your path. You can add it to the end of your existing path (the $path represents this) by issuing the command: % set path = ($path ~/units174/bin) Test that this worked by trying to run units in any directory other that where units is actually located. % cd; units HINT: You can run multiple commands on one line by separating them with a semicolon. To add this path PERMANENTLY, add the following line to your .cshrc AFTER the list of other commands. set path = ($path ~/units174/bin)

1.What is vi ? vi is a Visual Editor (hence the name -- vi for VIsual). 2.What is a visual editor (as opposed to a non-visual one)? Visual editors are ones that let you see multiple lines of the document that you are editing as you edit it. This seems pretty common in most editors today, so the idea of a non-visual editor is a little strange. Examples of non-visual editors are sed, ex, ed, and edlin (the last one being the editor shipped with DOS until relatively recently.) vi was written by William Joy as part of the bsd distribution of Unix. It was later used by AT&T, and has been standard Unix since. 3. What is the big deal about vi? Why does anyone use it? vi is the default visual editor under Unix, and is therefore shipped with all recent versions of Unix. (Recent being defined as post 1984 or so.) This means that whenever you run across a machine that is running a Unix of some sort, you will know that you have a powerful editor at your finger tips. Why else? vi is a powerful editor. Also,

once you know vi, you can edit files really quickly, as it is extremely economical with the keystrokes. Due to its different modes for inserting and issuing commands, it is much faster than most non-mode based editors. It is also a very small editor. (The version on my machine is 200k) Also, it can do almost anything, as long as you know how to get it to do what you want. Furthermore, as an editor it allows a lot of interaction with the Unix operating system. It allows you to use many of the powerful Unix utilities from within vi. It's possible to, from within vi, kill off a list of specific processes that you want to kill. If you haven't given yourself permission to write to the file you're editing by accident, you can change the permission without leaving vi. vi works by having commands that work on objects. By learning only a few commands and a few objects you can learn how to do a lot of things, simply by combining the commands and the objects. Even the commands are separated into subcategories. For example, the movement commands and the modification commands are different. If you know that d is the command to delete, and j is the command to go down a line, and you know how to combine them (dj), you can delete down one line. When you use numbers it gets even more powerful. d5j will delete 5 lines below you. Then, once you learn the character for "paragraph" (}), you already know how to delete 5 paragraphs. 4. Wow! This sounds great! Is there any reason not to use vi? Yes. There is a very good reason. It can be somewhat hard to learn, and until you do so, it will be slow and painful. Once you learn it, it will be faster, but the process of learning it is slow. I've been asked if vi was an easy editor to learn, whether it was intuitive or not. My general response to this question is: "Yes, some of us think so. But most people think that we are crazy." 5. What different operating systems is vi available for? Unix. That's it. (Well, technically, the 4.3BSD version included support for VMS as well.) However, there are many, many clones of vi that are available for different operating systems. I personally have used vi clones under: Unix, Dos, OS/2, Mac System 7. (See below for a

list of specifics.) 6. Okay, you've convinced me. I'm going to learn vi. Where do I start? Well... That's a tricky one. There are many good books out there that cover vi; most books on Unix have at least one chapter devoted to it. There are also many books devoted specifically to vi. I don't have any preference, so your best bet might be to ask your local vi guru where they learned. Also, play around. Fire up vi with a non-important document (your dissertation is NOT a good document to learn vi with...) and play around. I can't imagine anyone learning vi without playing around with it quite a bit. Remember, if you get confused, just hit the Escape key a couple of times, and you'll be in command mode again. I should mention at some point, and I guess here is as good a place as any, that people who think they might want to do Unix system administration, or any type of configuration of Unix machines will probably also want to learn ed or ex, as some versions of Unix do not put vi in the root partition, and one might be stranded without it at some point. Ed is a good choice. 7. What are some of the vi clones that are available? Just to list a few: STvi (STevie), elvis, vile, vim, and nvi, xvi. elvis is available for: Amiga, DOS, OS/2, Unix, VMS, Atari, Psion3a Handheld. Stratus machines running VOS can get elvis at: ftp://ftp.stratus.com/pub/vos/tools/tools.html Lemmy is available for Win95/NT at: http://www.accessone.com/~jai nvi is the vi that ships with BSD 4.4. STevie is available for: Atari ST, DOS, Unix, Macintosh. MacOS is available at any info-mac mirror in /info-mac/text (Such as ftp://ftp.hawaii.edu/pub/mac/info-mac/text)

Stratus machines running VOS can get STevie at: ftp://ftp.stratus.com/pub/vos/tools/tools.html vile is available for: BeOS, DOS, OS/2, Unix, VMS, Window95, WindowsNT The source is available at: http://dickey.his.com/vile/vile.html. xvile, a X-windows aware version of vile exists, as well. Vim is available for: AmigaOS, Atari MiNT, BeOS, DOS, MacOS, OS/2, Unix, VMS, Windows General information, documentation and much more about Vim is on http://www.vim.org/ The Vim Pages A list of sites which mirror Vim is available at: http://www.vim.org/dist.html Vim Distribution Page There are three mailing list for Vim: "VIM announcements list" vim-announce@vim.org "VIM help mailing list" vim@vim.org "VIM development list" vim-dev@vim.org Information on subscription is on page http://www.vim.org/mail.html viper is available for GNU Emacs. ftp://ftp.cs.sunysb.edu/pub/TechReports/kifer/viper.tar.Z xvi is available for: DOS, Unix. Mortice Kern Systems (support@mks.com), who I have absolutely no affiliation with, offers a commercial version of vi for DOS/Windows, OS/2, and WindowsNT. It is included as part of the MKS Toolkit (a set of Unix-like tools for Windows) and cannot be purchased separately. There are some differences between the different vi clones. Many offer improvements, but most still allow the commands that are listed in this document, but there may be some differences. Refer to the documentation that comes with the clone for details. 8. Learning vi. These are some basic hints for the novice vi user. First, keep a

command summary with you at all times. A quick reference guide/command summary is included later on. Second, get a good book that covers vi. This document is not the best way to learn it (at least not yet.) I'm not sure if this document should teach people to to use vi from scratch, as there are many good books on it already. However, there are hints here. As for choosing a book, the standard rules apply: look at it before buying it. See if any of it makes sense to you. Make sure that it has exercises that you can practice with. Compare it with other books -- after all, vi can be very confusing, and you want to make sure that it is the book that is confusing, and not just that you underestimated the difficulty of learning vi. Also, seek out vi learn or vi tutor, programs designed to teach you the basics of vi. 9. What games will help me learn vi? This may seem a bit silly, but there are many games on Unix systems that can help you learn to use vi. These help particularly with the basics. Although I don't know of any games that help with every vi command, I do know of a few that will help you learn to use hjkl to move the cursor around. NetHack, a rogue-like game, is particularly good for this, as it is a large game and can be entertaining for quite some time. Nethack is available from ftp://ftp.uu.net/ in /pub/games/nethack. Not to make the other games sound worse, but some other ones are: rogue, moria, omega, worm, and snake. Another fun thing to do to learn vi better is to play a game with friends to figure out the least number of vi keystrokes needed to do a specific task in vi. 10. What is the difference between Command mode & Insert mode? Often cited as one of the main problems with vi, and equally often cited as being one of its best strengths, vi differentiates between a "Command mode" and an "Insert mode". Understanding this difference is VITAL to learning vi. When one starts vi it starts in command mode. In this mode, one can move around the file, and issue commands to change certain areas of the text, cut, copy and paste sections of the

text and do much more. Insert mode is where one can actually insert text. In other words, command mode is used to move around the document, and insert mode is used to type text into the document. Commands such as: a, i, c, C, O, o and others will switch one from command mode to insert mode. <Esc> or <ctrl-c> will take one out of insert mode and return one to command mode. Get used to this distinction. It is one of the things that makes vi different from most other editors. It also allows one to do a lot of things without taking one's hands from the standard keyboard position. For novices it is often nice to know what mode you are in. If you type: "echo set showmode >> $HOME/.exrc" at the Unix command line, it will make it so that each time vi is started it will default to showing the mode on the bottom right of the screen. (To understand what this is doing, see the sections on "setting up a .exrc" and the "set options.") If it does not show anything in the bottom right, it means that you are in command mode. I call a few different modes (append, open and insert) "insert mode" in this document. 11. Wait, my keyboard doesn't have a <Esc> key! What should I do? Try hitting <ctrl-[> instead. If your keyboard has a <Meta> key, try that. If you don't have a <Meta> key, many keyboards use <Alt>, <Diamond>, <Start> or <Menu> as a <Meta> key (however, if you've got any of those keys, you almost certainly have an <Esc> key). If neither of these work, try <ctrl-3>. Some DEC terminals use the F11 key as escape. 12. What are all of those ~s? They're just there to let you know where the bottom of your file is, they are not actually in your document, and you do not need to worry about them. 13. I can't get used to using hjkl, do you have any suggestions? First, if your terminal is set properly and you have a good connection, you should be able to use the arrow keys. However, if you think that you will be using vi a lot, then it makes sense to learn hjkl, as they are faster to type. Also, there are occasions where you

may have a bad connection and the ESC sequences may get lost. Here is a simple mnemonic to help remember this: j extends below the line, and k above the line when written by hand. 14. How do I quit without saving? :q! will do it. 15. How do I insert a file? :r <filename> For example, to insert the file /etc/motd, type: :r /etc/motd This will insert the file at the current location in the file you are working on. If you specify a number before the r, it will insert it at that location in the file. 13. How do I search for text? /<text> will search forward. ?<text> will search backwards. ?? or // will repeat the last search. It is worth noting that these are pretty much standard in Unix. In addition, in vi, n will repeat the last search in the same direction as the original search. N will repeat the last search pattern in the opposite direction of the original search. For example /foo will find the next occurrence of "foo" from where you are. n will find the one after that. N will take you to the first occurrence. Hitting N a second time will get the same result as ?foo would have in the first place. Regular Expressions may be used within searches. 14. How do I search for a control sequence? /<ctrl-v><ctrl-<seq>> <ctrl-v> will tell vi to take the next character literally, and not to take it as a command.

15. How do I reformat text? If your computer has the program fmt on it, all you need to do is type !}fmt from command mode (without a : before it). This will reformat the text from the current location until the end of the paragraph. If your machine does not have fmt, you need to find a similar program. (I gather there are many such programs available from the public domain, but I do not know much about them.) You may also want to look into par. Par is similar to fmt in function, but has more feature. Par can be downloaded from: http://www.cs.berkeley.edu/~amc/Par. 16. How do I copy text? Okay, this might be a bit complicated. Take from this section what you can, and reread it a few times. Also, experiment. "<letter>yy will copy one line of text into register <letter>. (A register is vi-lingo for a place to store data that was cut or copied.) <letter> must be between a and z. "<letter>dd will delete one line and place it in register <letter>. You may use a number before the yy or dd to specify the number of lines. Using an uppercase <letter> will append the text into the register leaving what was there before. "<letter>p will put the text after the cursor. "<letter>P will put it before the cursor. If the register contains the beginning or end of a line, the line will be placed on another line as appropriate. Y may be used as a short cut for yy. In addition, y$, yH, yM, etc. are valid, as are the equivalent d commands. For quick cuts and pastes, no register need be specified. In this case, no appending is allowed, and the register will be removed if another delete command is given. (Including x). For example, to move the previous paragraph, one would go to the top of the paragraph, type "a13dd, move to the position in which one wishes to put the paragraph, and then type "ap to put it below the current line. Now, presumably you want to be able to cut and paste into areas that are not just the end of the line. In order to do this, use m<letter> to mark an area. This letter may be the same as a cut/copy register, they are stored in different area of memory. Then, type "<register>[y

or d]`<letter>. Where <register> is the register to put the text into, <letter> is the letter used to mark, and y or d as appropriate. 17. Ahhhh!!! I just hit dG and lost my dissertation! What can I do? (Or, I've just made a mistake, what should I do?) u will undo the last command. U will undo changes to the current line. (Granted, a one line dissertation would not be much.) :e! will reload the current document without saving any changes. In addition, deleted text gets stored in the registers numbered from 1 to 9. "<n>p will put the last nth deletion. You can quickly search the registers by trying one, hitting u, and trying the next. (In order to expedite this, vi uses . slightly differently than normal. Instead of repeating the last command, it will try the next register, so all you need to do is: "1p u . u ., etc. until you undo the delete you want to undo.) 18. vi appears to be frozen or acting strange, what can I do? (Also, I can't get rid of the colon prompt, now what?) If vi appears to have frozen, make sure that you haven't hit <ctrl-S> by mistake. In order to undo a <ctrl-s>, hit <ctrl-q>. If there is a colon and you can't get rid of it, you've entered ex by accident. Generally this happens by hitting "Q" from command mode. Just type vi to get back into vi. 19. I've just written my dissertation and have been told that I need to have each section in a different file, what should I do? :[m],[n]w <filename> will save between lines m and n to <filename>. This line numbering method works for almost every : command. If you use :[m],[n]w >> <filename> it will append it to the file. 20. What's the deal with all of these : commands? The commands that follow a : are commands from the ex editor. These allow a lot of flexibility and power. For example, there are many different ways to search and replace, all of which have some similarities (in fact, they are in some ways the same...) 21.Argh! vi has gone crazy! None of the commands work! Now what?

The most common time for vi to act insane when it comes to typing is when the caps lock key has accidentally been hit. Many keyboards on Unix servers have caps lock and control in the opposite position from many PCs, causing people to occasionally hit it. Just for fun, try navigating in vi with the caps lock on sometime. 22. How do you do a search and replace? Well, there are a few methods. The simplest is: :s/old/new/g But, this only does it on the current line... So: :%s/old/new/g In general: :[range]s/old/new/[cgi] Where [range] is any line range, including line numbers, $ (end of file), . (current location), % (current file), or just two numbers with a comma or semicolon between them. (Or even: .,+5 to mean the next five lines). [cgi] is either c, g, i, or nothing. c tells vi to prompt you before the changes, g to change all of the occurrences on a line. (type yes to tell vi to change it.) i tells vi to be case insensitive on the search. The g after the last slash tells it to replace more than just the first occurrence on each line. Another method is: :g/foobar/s/bar/baz/g This searches for foobar, and changes it to foobaz. It will leave jailbars alone, which the other method will not. Unfortunately, if jailbars appears on the same line as foobar, it will change, too. Of course you can also use regular expression search patterns, and a few other commands in the replacement part of the text. If you use \( and \) in the pattern to escape a sequence (and use \1, \2, etc., you can do lots of nifty things. For example: :g/foo/s/^\([^ ]*\) \([^ ]*\)/\2 \1/ will swap the first and second words on every line containing "foo".

Special sequences allowed are: & everything which was matched by the search \[1-9] The contents of the 1st-9th \(\) pair \u The next character will be made uppercase \U The characters until \e or \E will be made uppercase \l The next character will be made lowercase \L The characters until \e or \E will be made lowercase \[eE] end the selection for making upper or lowercase 23. My / key is broken! How can I search and replace? Well, okay, it doesn't really need to be a /. Lots of things will work fine. (letters, numbers and a few other things won't...) 24. How do I run a program from within vi? :!cmd will run the program cmd. :sh will run an interactive shell. Within this shell, you may, if you want, run vi again. This is particularly useful when you are editing makefiles and config files for programs in an attempt to get a program to compile. The advantage over :e is that you do not need to save the file, and it will be in its old place when you exit the shell. (I advise saving the file anyway...) 25. Ahhh!! I was writing my dissertation, and the computer crashed! Well, you should get mail about this, but you should be able to recover the file by typing vi -r <filename> where <filename> is the name of the file that you were editing at the time of the crash. vi -r will give you a list of files that can be recovered. 26. Any tips for making vi programmer friendly? :set ai will make it auto-indent for you. :set sw=# where # is a number will set the shiftwidth (tabwidth). You can then use <<, >> to shift a line left or right. Plus, you can use <% to shift a {, ( or [ set left or right (with >%). You must be on top of the specific {, }, (, ), [ or ] of the pair to shift them.

:set sm will show the matching {, ( or [ when you type the closing one. :set lisp will make some changes that are useful for lisp programming. () will move back and forth over s-expressions, and {} will move without stopping at atoms. 27. Macros -- How do I write them? :map <lhs> <rhs> where <lhs> is up to ten characters and <rhs> is up to 100. This will make it so that whenever you type <lhs> it will replace it with <rhs>. All macros should start in command mode (except those defined with map!), but may end in any mode you desire. Remember to use <ctrl-v> before any control characters that you may use. If you are using an Ex command, such as |, it needs to be escaped while vi is scanning the line. You should map it as :map foo <ctrl-v><ctrl-v>|. :unmap <lhs> will remove the macro. :map! <lhs> <rhs> will make <lhs> insert <rhs> into the text of the document. map! macros may have lhs's that are much longer. 28. How do I make a function key a Macro? If <lhs> is #n where n is 0-9, it will be mapped to the appropriate function key. 29. Is there anyway to abbreviate text? Yep, of course. This is vi, it can do anything. :ab email ellidz@midway.uchicago.edu will make it so that whenever you type email as a specific word, it will extend it to the entire unabbreviated word. :una email will unabbreviate it. 30. How do I spell check the current document? Here is a macro to do it. These should be put in your .exrc file. (More on .exrc files later on.) It is a pretty simple macro, it just calls ispell on the current file. Of course, to use this you need ispell on your system. To use it, just hit V with vi. (V is not used by vi, so it makes a good key.) map V :w<enter>:!ispell % <enter>:e!<enter><enter>

The second <enter> makes it so that one does not need to hit return after it is done checking the spelling. 31. How do I get rid the ^M's at the end of each line of my file? How do I make a macro to do it? These generally appear from DOS files that get converted to Unix. They're easy to get rid of. :%s/<ctrl-v><enter>//g will do it. The macro bit is a bit trickier. Not something that most people can guess on their own. Here it is: map v :%s/<ctrl-v><ctrl-v><ctrl-v><ctrl-v><ctrl-v><enter>//g Yes, that's right. 5 of them. The last one is to escape the enter. Two of the other four are to escape the other two <ctrl-v>'s. Since the macro gets read on the ex line, you need to have two <ctrl-v>'s (since you are searching for <ctrl-v> <enter> to replace it with nothing...) In general, if you are having trouble with a macro that uses the ex line, you need to escape things a lot. Sometimes it is quicker to just keep throwing <ctrl-v>'s in until it works. 32. I've got a hardcopy terminal, can I still use vi? Okay, okay, so I don't expect anyone to actually ask this... But, I thought it was bizarre enough to throw in anyway. (And, it actually answers a very common question...) vi will start up in a specific mode, called "open mode" in this situation. Things work more or less the same. Deleted characters will appear on your print out as \'s. vi will act as if the size of the window is only one line. ^r will retype the current line. z redraws the window around the current line. 33. Oh, okay, is THAT what open mode is? But I don't have a hardcopy terminal, and it still starts in open mode! Well, what is happening here is that vi doesn't know what type of terminal you have. It decides that in this situation the best thing to

do is to assume that you have the worst terminal possible. This might not seem useful, as not very many people need open mode, but it also is the mode that needs to know the least information about your terminal. Now, how to deal with it. It is possible to change it for the specific session, but in general, this is not useful. If you know your terminal type, you can set it from the Unix prompt (setenv TERM <termtype> under csh and it's variants, and: TERM=<termtype> ; export TERM under sh and its variants.). Better yet would be to edit your .profile or .cshrc to include this so it is automatically done for you when you login. (Of course, you need to either know ed or be able to set it at the Unix prompt before you'll be able to edit the file...) If you do not know your terminal type, try vt100. Most modern terminals and terminal emulators can emulate vt100. If this does not work, find someone to help you. 34. - How can I get the source code to vi? The source code to the original vi is available from: <http://ex-vi.berlios.de/>. You may also want to look at the source for some of the various vi clones. 35. More advanced topics in vi. 36. I see that sections are defined by SHNHH HU and paragraphs by IPLPPPQPPLIbp by default? What language is that in? What in the world does it mean? Man pages are written in a language called nroff/troff. Nroff is a general purpose text formatting language, similar to TeX. What does this have to do with vi and the sections? Use the Unix more command to look at a man page (say, /usr/man/man1/vi.1 or something). You'll see parts of the page split into sections, like .SH Name. The .SH is defining a section of the man page. Notice that SH is the first two characters of the section set option. The section and paragraph sections are defined by a listing of pairs of macros for nroff/troff. The next section will start with a period and then any of the pairs of letters that the section is defined as.

Paragraphs work the same way -- except that a blank line is also considered a paragraph break. 37. But when I program, I've noticed that I can use ]] and [[ to move between functions. My functions don't have .SH or anything at the beginning, what gives? Luckily for many C programmers, an open curly brace at the beginning of a line is also defined as a section break. 38. How do I work with multiple files at the same time? vi allows for multiple files to be open at the same time. Unlike many editors, you only see one file at a time. If you start vi with multiple files on the command line they'll all be opened up. You'll start out in the first file, and you can move to the next file by typing :n. If you've made changes to the current file that you don't want to keep, you can go on by using :n!. Note that this will discard any changes that you've made. If you want to save, you need to use :w first. 39. So, I've started up vi, but now I want to be able to edit another file. How do I do this? :n <filename> will load that file into vi. You'll need to save your current file. 40. How can I get back to the first file, though? :e # will edit the last file that you were editing. You can use this to swap back and forth quickly between two different files. If you are editing many files, you can use :n to cycle between them. 41.But I'm only wanting to edit one file at a time. I've got one open and I want to switch permanently to another file. How do I do that? Just use :e <filename> and it will load it up. 42. How do I add another file into the middle of my current file? :r <filename> will read in a new file at the current location. It is

worth noting that Unix in general deals with the output of commands as files in many respects. Because of this, you can easily read in the output of a command into the file: :r !<command> will read in the output.

You might also like