You are on page 1of 141

HANDOUT

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

UNIX COMMANDS AND UTILITIES

Edition : 04

770 00440 0490-VHBE

ALCATEL UNIVERSITY

The Alcatel University put in a great effort to give you this document. In case you have any remarks, do not hesitate to send us your comments. Our Training Directory describes all training programmes and modules this document (and others) is used in. This document was especially written for use during class instruction. The contents of this document is generic. It deals with concepts and principles, rather than with the latest releases of and modifications to the product delivered to the customers.
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

International audiences use this document. It is therefore written in a clear, concise and above all, consistent language.

ALCATEL UNIVERSITY

II

770 00440 0490-VHBE

TABLE OF CONTENTS
1 1.1 1.2 1.3 1.4 1.5 2 INTRODUCTION.............................................................................................. 1 Syntax notation................................................................................................. 1 History .............................................................................................................. 2 Today ............................................................................................................... 3 The UNIX style ................................................................................................. 4 UNIX documentation ........................................................................................ 5 THE STRUCTURE OF THE UNIX SYSTEM .................................................... 6

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

2.1 The kernel ........................................................................................................ 6 2.2 The shell........................................................................................................... 6 2.2.1 The BOURNE shell .................................................................................... 6 2.2.2 The C shell................................................................................................. 7 2.2.3 The KORN shell ......................................................................................... 7 2.3 Utilities.............................................................................................................. 7 3 THE DIRECTORY TREE AND THE FILE SYSTEMS ...................................... 8 3.1 Different kinds of UNIX files.............................................................................. 8 3.2 The directory tree ............................................................................................. 9 3.2.1 Directory and file specification ................................................................... 9 3.2.2 The directory /bin .................................................................................. 10 3.2.3 The directory /usr .................................................................................. 10 3.2.4 The directory /dev .................................................................................. 10 3.2.5 The directory /tmp .................................................................................. 11 3.2.6 The directory /etc .................................................................................. 11 3.3 Login directory - Home directory - Working directory..................................... 12 3.4 The file systems ............................................................................................. 12 3.4.1 File system characteristics....................................................................... 12 3.4.2 Mounting and unmounting file systems.................................................... 13 3.5 Hard links and Symbolic links......................................................................... 15 3.5.1 Hard links................................................................................................. 15 3.5.2 Symbolic links .......................................................................................... 16 4 4.1 4.2 4.3 5 5.1 5.2 5.3 5.4 LOGGING IN, LOGGING OUT ...................................................................... 18 How to log in ?................................................................................................ 18 Shell start up files ........................................................................................... 18 How to log out ? ............................................................................................. 19 COMMONLY USED UNIX COMMANDS ....................................................... 20 Command format............................................................................................ 20 Where are commands stored ? ...................................................................... 21 Getting help : man........................................................................................... 22 Display the current date and time : date ....................................................... 22

770 00440 0490-VHBE

III

ALCATEL UNIVERSITY

5.5 5.6 5.7 5.8 5.9 5.10 5.11 5.12 5.13 6


2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

Display the calendar : cal ............................................................................. 23 Get the terminals name : tty ........................................................................ 24 Set the options of the terminal : stty ............................................................ 24 List who is on the system : who...................................................................... 25 Log in as another user : su ............................................................................ 25 Change password : passwd ....................................................................... 26 Change of group : newgrp.......................................................................... 27 Information on the active processes : ps .................................................... 28 Terminate a process : kill........................................................................ 28 FILE MANIPULATION COMMANDS............................................................. 30

6.1 Print working directory : pwd .......................................................................... 30 6.2 List the contents of a directory : ls ................................................................ 30 6.3 Change working directory : cd ....................................................................... 32 6.4 Make a directory : mkdir ............................................................................... 32 6.5 Remove a directory : rmdir........................................................................... 32 6.6 Determine nature of a file : file ................................................................... 34 6.7 Display the contents of a file........................................................................... 35 6.7.1 cat ....................................................................................................... 35 6.7.2 Display a file one screen at a time : more ............................................... 36 6.7.3 Display the end of a text file : tail ......................................................... 37 6.7.4 Display the beginning of a text file : head................................................ 37 6.7.5 Display a file with pagination : pr ............................................................ 37 6.8 Print files : lp ................................................................................................. 38 6.9 The a2ps utility .............................................................................................. 38 6.10 Copy a file : cp ............................................................................................ 42 6.11 Move a file : mv............................................................................................ 42 6.12 Remove a file : rm ....................................................................................... 43 6.13 Sorting input : sort .................................................................................... 44 6.14 Report the differences between files : diff ............................................... 46 6.15 Display common lines in two sorted files : comm ......................................... 48 6.16 Joining two files : join ............................................................................... 49 6.17 Search a file for a pattern : grep ................................................................ 51 6.18 Remove adjacent repeated lines in a sorted file : uniq.............................. 52 6.19 Translate characters : tr ............................................................................ 53 6.20 Word count : wc........................................................................................... 54 6.21 Compressing files : pack ............................................................................ 55 6.22 Display file in octal format : od .................................................................... 56 6.23 Finding files : find ..................................................................................... 57 6.24 Change ownership of file : chown and chgrp ............................................ 59 6.25 Command df .............................................................................................. 59 6.26 Command touch ........................................................................................ 60 7 FILE PROTECTION ....................................................................................... 62

ALCATEL UNIVERSITY

IV

770 00440 0490-VHBE

7.1 7.2 7.3 8 8.1 8.2 8.3 9 9.1 9.2 9.3 9.4 9.5 9.6 9.7 9.8 9.9 9.10 9.11 9.12 10

Introduction..................................................................................................... 62 Changing the protection bits for files to be created........................................ 62 Changing the protection bits of existing files .................................................. 64 COMMUNICATION UTILITIES ...................................................................... 66 The write utility ............................................................................................ 66 The talk utility .............................................................................................. 66 The mail utility .............................................................................................. 67 THE vi EDITOR ............................................................................................ 68 Introduction..................................................................................................... 68 Cursor movements ......................................................................................... 69 Screen movements ........................................................................................ 69 Inserting text................................................................................................... 70 Deleting text ................................................................................................... 70 Replacing text................................................................................................. 70 Search commands ......................................................................................... 71 Moving text ..................................................................................................... 71 Copying text ................................................................................................... 71 Joining lines ................................................................................................ 71 Executing a shell command ........................................................................ 72 Other interesting commands....................................................................... 72 SHELL SCRIPTS ........................................................................................... 74

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

10.1 How to execute a shell script ?.................................................................... 74 10.2 SHELL variables.......................................................................................... 75 10.3 Exporting variables...................................................................................... 76 10.4 Positional parameters ................................................................................. 77 10.5 Interactive input........................................................................................... 78 10.6 Comments................................................................................................... 78 10.7 Simple calculations : expr .......................................................................... 78 10.8 if and test instruction........................................................................... 80 10.9 case instruction ....................................................................................... 82 10.10 for instruction ......................................................................................... 83 10.11 while instruction..................................................................................... 84 10.12 true command........................................................................................ 84 10.13 sleep instruction..................................................................................... 84 10.14 exit command........................................................................................ 85 10.15 Echo text on standard output ...................................................................... 85 10.16 More on quotes ........................................................................................... 86 10.16.1 Double quotes ...................................................................................... 86 10.16.2 Single quotes........................................................................................ 86 10.16.3 Using quotes within quotes................................................................... 87 10.16.4 Backward quotes .................................................................................. 87 10.17 Set the options for the terminal to switch off echo: stty ............................ 87

770 00440 0490-VHBE

ALCATEL UNIVERSITY

11 11.1 11.2 11.3 11.4 12

THE KORN SHELL ........................................................................................ 88 Running the Korn shell................................................................................ 89 Edit the command line using vi commands................................................. 89 History mechanism...................................................................................... 90 Aliassing...................................................................................................... 91 THE emacs EDITOR FAMILY ....................................................................... 92

12.1 Introduction ................................................................................................. 92 12.2 Keyboard-based command input ................................................................ 93 12.3 Starting Xemacs on the VE desktop............................................................ 94 12.4 Abort command in progress........................................................................ 94 12.5 Ways to open an existing file....................................................................... 94 12.6 Start a new file ............................................................................................ 95 12.7 Buffers and Windows .................................................................................. 95 12.8 Moving the cursor in a Buffer ...................................................................... 96 12.9 Search for a string....................................................................................... 96 12.10 Getting Help on screen ............................................................................... 96 12.11 Basic editing in a buffer............................................................................... 98 12.12 Search/Query and Replace......................................................................... 98 12.13 Print a buffer................................................................................................ 98 12.14 Search using Regular Expressions ............................................................. 98 12.14.1 Syntax of Regular Expressions............................................................. 99 12.14.2 Regular expression example .............................................................. 103 12.15 Macros ...................................................................................................... 104 12.16 Emacs modes ........................................................................................... 104 12.17 A UNIX shell in a buffer ............................................................................. 105 12.18 Emacs keystrokes tables (default key bindings) ....................................... 106 12.19 A few examples of customising Xemacs/GNU emacs using emacs lisp... 119 12.20 References for more detailed information................................................. 121 13 13.1 13.2 13.3 13.4 14 SOME COMMANDS RELATED TO NETWORKING................................... 124 Command ypcat ...................................................................................... 124 Command rlogin.................................................................................... 125 Command telnet.................................................................................... 125 Command ftp .......................................................................................... 127 SOME COMMANDS RELATED TO XWINDOWS ....................................... 130

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

14.1 Why a Graphical User Interface (GUI) ? ................................................... 130 14.2 What is a GUI? .......................................................................................... 131 14.3 Command xterm........................................................................................ 131 14.4 Command xkill........................................................................................... 132 14.5 Running an X application on a remote machine but displaying the window(s) on the local workstation.......................................................................................... 132 15 THE CRiSP EDITOR.................................................................................... 134

ALCATEL UNIVERSITY

VI

770 00440 0490-VHBE

15.1 15.2 15.3 15.4

Start CRiSP............................................................................................... 134 Use the HELP system ............................................................................... 134 Look at a CHILL listing and search in it..................................................... 134 Edit a CHILL text ....................................................................................... 136

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

770 00440 0490-VHBE

VII

ALCATEL UNIVERSITY

INTRODUCTION

1 INTRODUCTION
1.1 Syntax notation

The following notation is used to express the syntax: courier font is used for strings that should be used LITERALLY e.g. man , the UNIX manual information command name times roman italic is used for strings that describe what you have to type. e.g. man nameOfCommandToExplain
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

[ ] enclose something optional ([ ] are the square braces themselves) { } enclose something that must be present minimum once, and may be repeated infinitely ({ } are the curly braces themselves) | separates alternatives ( | is the vertical line itself) the alternatives are the syntax notation elements immediately to the left and right of the |. Example: the syntax for an identifier in the C language: letter | underscore [{letter | digit | underscore}]

770 00440 0490-VHBE

ALCATEL UNIVERSITY

INTRODUCTION

1.2

History

The first UNIX system was developed by two engineers of the Bell Laboratories of AT&T : Dennis Ritchie and Ken Tompson. They started their work because they were not satisfied with the existing operating systems. Their first system (circa 1969-1972) was written in assembler and ran on the DEC PDP-7 and PDP-9 computers. It was still a single- user operating system. Later systems were multi-user systems and ran on PDP-11/34, /40, /45, /60 and /70 computers. Together with Brian Kernighan, Dennis Ritchie created a new high level programming language which they baptised C. During the summer of 1973, they rewrote as much as possible of the UNIX programs as well as the greater part of the kernel in this new language. The resulting kernel was one third larger than the original one, but in the meantime a lot of improvements had been achieved so that this increase in size is not important. More attractive was the fact that only a very small part of UNIX was written in assembler. The source of the kernel actually contains 10000 lines of C-code and only 1000 lines of assembly code. The only thing needed to implement the same system on another machine is to rewrite this small part and write a compiler for this brand new C language. Many people outside AT&T, both from university and business environments became interested in this new operating system. Especially the university of Berkeley did a lot of work on UNIX. They came out with a version of UNIX to run on a VAX machine, at that time DECs newest computer. These days, the University of Berkeley is still carrying out a lot of research on UNIX.

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

ALCATEL UNIVERSITY

770 00440 0490-VHBE

INTRODUCTION

1.3

Today

We can say that there are two major streams of UNIX systems : the AT&T line with their System V and the Berkeley line with their BSD Unix. System V based systems : Interactive System (PC) XENIX (PC) HP-UX (Hewlett-Packard) Solaris (Sun) SCO Unix (PC) ...
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

BSD based systems : ULTRIX (VAX) SUN OS (Sun) Apollo (Apollo) ...

System V.4 is said to be a first step towards a unified UNIX. System V.5, which is already announced, will be a rewrite in C++. On the BSD side, 4.4 BSD is announced. Communication facilities will be the most important asset of this new release. OSF/1 is worth to be mentioned too. OSF stands for Open Software Foundation. The aim of this non-profit organisation is to throw technical products on the market which run in a distributed environment. The members of OSF are all well known computer constructors (Sun excepted) and software houses. OSF writes a request for a certain technology and all members can do a proposition. At the end they all come to one integrated solution which will be the product. So is OSF/1 the operating system of OSF. It is a UNIX-like operating system, but not yet often used.

770 00440 0490-VHBE

ALCATEL UNIVERSITY

INTRODUCTION

1.4

The UNIX style

The first designers of the UNIX operating system preferred a sober style. They had a good knowledge of theory and they were sure that the computer could be a very fascinating tool. Being unsatisfied with the operating systems existing at that time, Dennis Ritchie and Ken Tompson created their own operating system.
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

UNIX is accurate and sober. It is not for inexperienced users, because of the absence of informative messages. That is why UNIX is said not to be user-friendly. The rule is : no news, good news. Because UNIX is designed by rather highly qualified and creative people, UNIX is no end product but, in the hands of a capable user, it is an extension to creative thoughts. Sometimes it is hard to realise the power of some command structures or programs. It takes some time and effort to appreciate the power of UNIX, but it is certainly worthwhile in the end.

ALCATEL UNIVERSITY

770 00440 0490-VHBE

INTRODUCTION

1.5

UNIX documentation

The standard documentation exists of 2 logical volumes : Volume 1 : Programmers Manual The Programmers Ma nual usually is divided into eight major sections, preceded by a table of contents and an index. Variations on this are possible. Section 1 : User Level Commands Section 2 : System Calls Section 3 : System Subroutines and Libraries Section 4 : File formats Section 5 : Miscellaneous Section 6 : Games Section 7 : Peripheral devices Section 8 : System Maintenance Volume 2 : Articles

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

Remarks : The sequence of the sections 4 to 7 in the documentation of BSD based systems differs from the sequence of SV based systems. The manual of the XENIX and SCO systems differs from the normal manual layout described above. When the system is configured well, the first volume of the manual is present online. You can consult the online manual by using the man command. Sometimes the online manual is not loaded in order to save disk space. A new development is to have all documentation online from CD-rom (e.g. Answerbook from Sun).

770 00440 0490-VHBE

ALCATEL UNIVERSITY

THE STRUCTURE OF THE UNIX SYSTEM

2 THE STRUCTURE OF THE UNIX SYSTEM


The UNIX system can be divided into two main parts : the kernel and the utilities. One of the most important utilities is the shell.

2.1

The kernel

The kernel is the heart of the operating system. It is a resident piece of software. All operating systems have a kernel, although it may have other names.
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

Its functions are : I/O processing Processes and Memory management IPC (Inter Process Communication)

2.2

The shell

The shell is the command interpreter of UNIX. It stands between the user and the kernel. If a user enters a command, the shell checks if the command is existing. If so, the corresponding system calls are executed by the kernel. If the command does not exist, the shell returns an error message. Thanks to the shell, there is no need for you to talk to the kernel directly using system calls. There are several shells available to UNIX users. The ones we will discuss are the BOURNE shell, the C shell and the KORN shell. The user may choose between the shells available on his system. 2.2.1 The BOURNE shell This shell is the default shell on most of the UNIX systems (exception : SUNOS). It is written by Stephen Bourne and now available on every UNIX system. The BOURNE shell is stored in the file /bin/sh. Characteristics of the BOURNE shell : good programming facilities, no history mechanism, no command line editing, default prompt : $.

ALCATEL UNIVERSITY

770 00440 0490-VHBE

THE STRUCTURE OF THE UNIX SYSTEM

2.2.2 The C shell On most UNIX systems, the C shell is available too. It is the default shell for SUNOS. The C shell was developed at the university of California at Berkeley and gets its name from its programming language, which resembles the C programming language in syntax. The C shell is stored in the file /bin/csh. Characteristics of the C shell : limited programming facilities (e.g. if statements can not be nested), history mechanism, command line editing for commands of the history list, good job control on systems which have in the kernel special services, otherwise no job control, default prompt : %. 2.2.3 The KORN shell

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

The KORN shell is a rather new shell based on the BOURNE shell. It was written by David Korn. It has all the advantages of the BOURNE shell and all those of the C shell. In the future, the KORN shell will be more and more distributed. In SYSTEM V.4, this shell is the default shell. It is stored in the file /bin/ksh. Characteristics of the KORN shell : good programming facilities, history mechanism, command line editing, good job control on systems which have in the kernel special services, otherwise no job control, default prompt : $.

2.3

Utilities

Utilities can be : compilers, editors, text processors, spreadsheets, ...or in fact any application.

770 00440 0490-VHBE

ALCATEL UNIVERSITY

THE DIRECTORY TREE AND THE FILE SYSTEMS

3 THE DIRECTORY TREE AND THE FILE SYSTEMS


3.1 Different kinds of UNIX files

A UNIX system uses three kinds of files : ordinary files, directory files, device special files.

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

An ordinary file is a file containing whatever information the user places in it, e.g. ASCII text or binary (object) programs. No particular structuring is expected by the system. A file of text simply consists of a string of characters, with lines demarcated by a special character : the newline character (the same character that we produce when typing Return (or Enter)). Binary files contain data as it will appear in the systems memory when the program starts executing. A few ordinary files have more structure. The structure is always controlled by the programs that use them, not by the system.

A directory file is a file the system manages, and through which the whole tree structure is linked together.

A device special file is like a port to a peripheral connected to the system. Information written to a special file will not be saved on disk, but it will be sent to the peripheral. All connected pheripherals are to be accessed in this way : floppy-disks, terminals, printers, tapeunits, etc. The beauty of this is that every program, working with files, can communicate with peripherals without having to take any special action in the program itself. (Of course, some things have no sense, e.g. editing a special file.)

ALCATEL UNIVERSITY

770 00440 0490-VHBE

THE DIRECTORY TREE AND THE FILE SYSTEMS

3.2

The directory tree

Each computer running UNIX has a hierarchical directory system, which is a tree structure. At the top, we have the root directory (denoted with a / character) and beneath the root we have files (leaves of the tree) and directories (nodes of the tree). Directories on their turn can have directories and files. The directory tree gives a uniform view of the available files and their organisation into directories regardless of the physical location of these files and directories (different disks or even different computers connected via a network). The first level of directories is standard to most UNIX systems:

/
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

bin

usr

dev

tmp

etc

3.2.1 Directory and file specification A file or directory name may contain any character except a / and a null character. It is better not to start a file name with a minus sign (see later). A distinction is made between uppercase and lowercase letters. A file or directory somewhere in the directory tree can be specified by using either an absolute or a relative specification: Absolute specification: starts from the root: /usr/wlan/sources/aprogram.c / characters are used to separate the components of the complete path form the root to the wanted file or directory. Relative specification: is relative to your current position in the directory tree called the working directory (see 3.3): When your working directory is /usr/wlan, you can specify the file relatively as follows: sources/aprogram.c The names . and .. have a special meaning :

770 00440 0490-VHBE

ALCATEL UNIVERSITY

THE DIRECTORY TREE AND THE FILE SYSTEMS

The name . is the abbreviation for the current directory, and the name .. is the abbreviation for the parent directory. 3.2.2 The directory /bin In this directory, most of the system binary files are stored.

3.2.3 The directory /usr


2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

In this directory, every user has his own user directory where he can freely arrange his data. / usr christine pascal sources a b c exec a b c c sources x y z exec x y z general f1 f2 f3 rudy prog prog1

Other directories : /usr/bin /usr/include /usr/man /usr/tmp /usr/mail

Contains commands not required to boot, restore, or repair the file system. Contains high-level C language header files; the shared definitions. Contains the manual pages. An alternative directory for placing temporary files. Used for the mail facilities for your mailbox.

3.2.4 The directory /dev All device special files are stored in the directory /dev. dev stands for devices. eg. /dev/tty01 /dev/lpr

ALCATEL UNIVERSITY

10

770 00440 0490-VHBE

THE DIRECTORY TREE AND THE FILE SYSTEMS

3.2.5 The directory /tmp Temporary files of users and utilities can be stored in this directory (eg. workfiles of editor, compiler and sort command). Most of the utilities delete their intermediate files immediately after utility ending. In a lot of systems, all remaining files in the directory /tmp are automatically deleted during the night.

3.2.6 The directory /etc The directory /etc is a typical system administrator and configuration directory. An example of a file in this directory is /etc/passwd which contains a record for each user defining specific properties for the user.etc is an abbreviation for et cetera. Note : As opposed to other operating systems, UNIX uses a single directory tree structure, i.e. multiple volumes/disk are hidden in 1 directory tree.

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

770 00440 0490-VHBE

11

ALCATEL UNIVERSITY

THE DIRECTORY TREE AND THE FILE SYSTEMS

3.3

Login directory - Home directory - Working directory

When a user logs in to the UNIX system, he begins to work in a particular directory. This directory is known as the login directory of the user. It is specified in the file /etc/passwd. The directory in which the user is working at a given moment is known as the working (or current) directory. The working directory is not fixed and may be changed by use of the cd command (see later). A relative pathname describes the path of directories starting from the working directory. The home directory is defined by the user as being the directory he most frequently uses at a given moment. Using the cd command without arguments, the working directory is automatically set to the home directory. If the user did not define his home directory, it is equal to his login directory. Defining the home directory in the BOURNE and Korn shell : HOME=/usr/rudy/prog Defining the home directory in the C shell : set home=/usr/rudy/prog Immediately after logging on, the login directory, the home directory and the current directory are the same.

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

3.4

The file systems

3.4.1 File system characteristics Physically, the directories and files can be on different disks and even on distant computers connected via a network. Per disk, directories and files (which form a tree with its own root) are stored in file systems. File systems (or a part of them) can be placed (mounted) at any node of the directory tree (mounting point). Making, mounting and unmounting file systems can only be done by the system administrator (root password). A file system is the primary organisation for file storage in UNIX. Each file system uses blocks of disk storage to store the data of files and directories and also its own housekeeping information: the superblocks and the inode area. We give some more details about these because this is needed to understand the concept of links discussed in paragraph 3.5.

ALCATEL UNIVERSITY

12

770 00440 0490-VHBE

THE DIRECTORY TREE AND THE FILE SYSTEMS

The superblocks are multiple copies (redundancy!) of the most vital information. They store information about the disks geometry (number of heads, cylinders, ), the location of the inode area and the head of the free disk block list. The inode area contains inode records, identified by their inode number, which contain information about a file (the access permissions for certain kinds of users, the owner of the file, the size of the file, the date and time of the last access to the file, where the files blocks are on the disk,). Directory file entries contain a file or directory name and the corresponding inode number. 3.4.2 Mounting and unmounting file systems
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

Although the mount and umount commands can only be used by somebody who knows the root password, we discuss them briefly here because this helps understanding the principles. We also briefly discuss automatic mounting of file systems when the computer is booted. Part of the power of UNIX stems from its flexibility in placing file systems anywhere in the directory tree. This is accomplished by mounting file systems. Before you mount a file system, you need to choose a mount point. A mount point is the directory entry in the directory tree where the root directory of the file system to be mounted will overlay it. A mount point may exist anywhere in the directory tree, but the root of the directory tree is of course reserved for the file system that holds the kernel files and other basic files. 3.4.2.1 Automatic mounting of file systems at boot time At boot time, the system automatically mounts the root file system with read-only privileges. This enables it to load the kernel and read critical startup files. Once it has bootstrapped itself, it uses the special file /etc/fstab (/etc/vfstab on Solaris). This file lists all the file systems that need to be mounted at boot time and their mounting point. Each file system to be mounted is listed in the fstab (or vfstab) file in the following format:

[hostname:]dirOfFilesystem dirToMount ftype parameters fs_freq fs_passno


Where: dirOfFilesystem

770 00440 0490-VHBE

13

ALCATEL UNIVERSITY

THE DIRECTORY TREE AND THE FILE SYSTEMS

Is the disk file system (or part of a file system) to be mounted. If it is a file system present on a distant computer in a network, it must be preceded by the distant computers hostname (e.g. server1:/dev/disk1) and the distant computer must have allowed this remote mounting (see 3.4.2.3 Allow remote mounting) dirToMount Is the mounting point in the directory tree ftype Is the file system type, e.g. ufs for a local Solaris file system or nfs for NFS (Suns Network File System for file systems present on distant computers in a network) or swap for swap partitions (used for swapping of memory contents to and from disk when the RAM memory size is not sufficient) or hps for hp-UX.
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

parameters Are the parameters passed to the mount command: see in 3.4.2.2 characteristics separated by commas fs_freq Is used by dump to determine whether a file system needs to be dumped fs_passno Is used by the fsck program to determine the order in which to check disks at boot time. 3.4.2.2 Manual mounting/unmounting of disk file systems To manually mount a disk file system, use the mount command with following format: mount [-F ftype] [ option ] [hostname:]dirOfFilesystem dirToMount Where: ftype See ftype in 3.4.2.1 (Automatic mounting at boot time) option -o characteristic [{,characteristic}] characteristic rw | ro | bg | intr rw: read/write ro: read only

ALCATEL UNIVERSITY

14

770 00440 0490-VHBE

THE DIRECTORY TREE AND THE FILE SYSTEMS

bg: background mount: if the mount fails, keep trying until success. intr: if a process has pending I/O on the mounted file system, it allows the process to be interrupted and the I/O call dropped. hostname Is the name of the distant computer. That distant computer must have allowed the remote mounting (see 3.4.2.3 Allow remote mounting). See the man pages for more details. The command mount without any parameters displays a list of currently mounted file systems.
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

To manually unmount a file system, you must first make sure nobody is using files of that file system. To unmount, use the umount command: umount dirWhereMounted 3.4.2.3 Allow remote mounting A computer acting as a server for other computers must allow the remote mounting of a file system by those other computers. This is done with the share command. See the man pages for details.

3.5

Hard links and Symbolic links

3.5.1 Hard links Since a directory entry points to a certain inode using the inode number and hence to file data on disk, it is possible for a number of directory entries in the same file system to point to the same inode, making the same information accessible via different file names. So, there can be different hard links to the same data. Why would we do something like that? There are two reasons why hard links can be useful: 1) Suppose we are working normally in a certain directory which we make our working directory but we have to access frequently a file that is located in an entirely different subtree

770 00440 0490-VHBE

15

ALCATEL UNIVERSITY

THE DIRECTORY TREE AND THE FILE SYSTEMS

of the directory tree but in the same file system. Instead of having to use a lengthy file specification each time we access that file we can make a hard link to that file in our working directory under a certain file name. Then we can use that local file name to access the file. 2) When we delete a file, the actual data will only be lost when we delete the last hard link to that data, causing the disk blocks and the inode to become free again. Hard links are created with the ln command Example: Given this directory listing using command ls -il (ask for a directory listing: see later for a detailed description of the ls command):
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

13180 -rw------ 1 userX groupY

42 May 12 13:04 hello

13180 is the inode number used by the file hello. When we now create a hard link: ln hello goodbye After a new ls -il we get: 13180 -rw------ 2 userX groupY 13180 -rw------ 2 userX groupY 42 May 12 13:04 goodbye 42 May 12 13:04 hello

Note that both file entries use the same inode number. Disadvantage of hard links: they cannot cross file system boundaries. 3.5.2 Symbolic links A symbolic link (sometimes referred to as a symlink) differs from a hard link because it doesnt point to the same inode but to a filename. This allows symbolic links to exist across file systems. Symbolic links are also created with the ln command but with option s. Example: A common thing users do is create a symbolic link for a directory that has moved. For example, if you are accustomed to accessing the directory for your home page in the subdirectory www, but at the new site you work at home pages are kept in the public_html directory, you can create a symbolic link from www to public_html using the command ln -s public_html www. Performing an ls -l (ask a directory listing: see later for the detailed description of the ls command) shows the link:

ALCATEL UNIVERSITY

16

770 00440 0490-VHBE

THE DIRECTORY TREE AND THE FILE SYSTEMS

drwx------ 2 userX groupY 512 May 12 13:08 public_html lrwx------ 1 userX groupY 11 May 12 13:08 www -> public_html

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

770 00440 0490-VHBE

17

ALCATEL UNIVERSITY

LOGGING IN, LOGGING OUT

4 LOGGING IN, LOGGING OUT


UNIX is a multi-user operating system. A consequence is that the user has to identify himself. In order to protect the user from others, a password must be given. 4.1 How to log in ?

Power the terminal on and press and release the Return or Enter key. Possibly, the user must connect himself to the system (ask other users). Afterwards, the login program will prompt login: So type your login name (user name). Your login name is a unique name that identifies you to the system and distinguishes you from other users.
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

Type after the word password: your password. Notice that the password is not echoed on the screen. If you do not have a password yet, you will be logged in immediately. Login name and password are given by the system administrator. On some computer systems, the terminal type is asked. If you do not know the answer to this question, ask the system manager. Afterwards, the login shell is started up. Which login shell is used for each user is determined in /etc/passwd (or in the network-wide password data).

4.2

Shell start up files

Depending on which login shell is used, the file .profile or .login is executed before the prompt is shown on the screen. These two files are the so called shell start up files and can be used to set the working environment to the wishes of the user, show some information messages, etc. The Bourne shell and the Korn shell uses .profile, and the C shell uses .login. A start up file must occur in the login directory. If it is not found, it is not executed. After execution of the start up file, the prompt is shown on the screen.

ALCATEL UNIVERSITY

18

770 00440 0490-VHBE

LOGGING IN, LOGGING OUT

In addition to the Korn shell .profile script file there can also be a .kshrc script file. This .kshrc file is executed whenever you start a new Korn shell process. The .profile file is only executed at a login. 4.3 How to log out ?

Logging out is done by pressing Ctrl-d (control d) or by typing exit. NEVER switch off the power of a workstation running UNIX without a proper shutdown, EVEN AFTER HAVING LOGGED OUT! There are several reasons why you should NOT switch off a workstation running UNIX without having done a proper shutdown (shutdown command): There could be users remotely logged on to that workstation and which are still running programs when you switch the workstation off!!! This could result in corrupted files for those users and even a corrupted file system (see second reason). UNIX keeps disk data in a RAM cache and when you brutally switch off the workstation the data still in the cache will not be written to disk, causing sometimes a corrupted file system or at least some corrupted files! WORSE, the workstation may have been configured as a SERVER for some other workstations and may normally NEVER be switched off!!! The shutdown command can only be given when you know the root password, so in principle a shutdown should only be done by the system administrator and you should leave the power ON!!!

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

770 00440 0490-VHBE

19

ALCATEL UNIVERSITY

COMMONLY USED UNIX COMMANDS

5 COMMONLY USED UNIX COMMANDS


5.1 Command format

The command must be entered after the shell prompt. Each shell has his own default prompt : KORN shell, BOURNE shell : $ C shell : % The default prompt can be changed by the user : BOURNE shell : PS1=Enter command > PS2=Continuation >
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

C shell : set prompt=Enter command > The format of a command is command [options] [arguments] command : Name of the command options : The purpose of an option is to specify a modification to the normal operation of the command. options usually consists of a leading minus sign or sometimes a plus sign, followed by one or more characters or digits, e.g.: -ag arguments : Arguments (or parameters) must be separated by one or more spaces or tab characters. Examples : date ls -l cp file1 file2 When explaining the different UNIX commands in the following pages, a description of the syntax will be given. This syntax is simplified and not complete. The purpose of this course is to give an overview of the commands and options mostly used and common to the different versions of UNIX. To have a full description of the UNIX commands available on your system, you are advised to consult the manuals.

ALCATEL UNIVERSITY

20

770 00440 0490-VHBE

COMMONLY USED UNIX COMMANDS

5.2

Where are commands stored ?

Except for some shell internal commands, a command is a program stored somewhere in the file system. The directories /bin and /usr/bin are used for this. The user can make his own commands. In this case he stores the command file in one of his own directories. The name of the command is the same as the name of the file. To execute a command : specify the full pathname of the file, or just enter the name of the command. (This last option is mostly used.) Specifying the full pathname, the system knows automatically where the command is stored. Specifying the name of the command, the system looks at the value of the PATH shell variable in order to find the command. The PATH variable comprises a list of directories. This list will be searched for an executable file with the same name as the command name. The first directory in the list will be searched first. In this way, a user can override a UNIX command by a self made version of it. To change the contents of the PATH shell variable : BOURNE shell or Korn shell: PATH=.:/usr/christine/bin:/bin:/usr/bin C shell : set path=.:/usr/christine/bin:/bin:/usr/bin The colon is used to separate the directory names. Remarks : A value of the PATH variable starting with : has the same meaning as if the value would start with .:. So, the search path :/bin:/usr/bin is equivalent to the search path .:/bin:/usr/bin. The current directory is not a part of the PATH by default.

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

770 00440 0490-VHBE

21

ALCATEL UNIVERSITY

COMMONLY USED UNIX COMMANDS

5.3

Getting help : man

Syntax : man [-s section] title When the system is configured well, the first volume of the manual is present online. You can consult the online manual by using the man command. Examples : man chmod Gives you the manual pages of the chmod user command man -s 2 chmod Gives you the manual pages of the chmod system call man -s 1 intro Gives you an overview of the contents of the first section
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

Movement through the text: To move 1 line further: Enter To move 1 screen further: space To move back: B To search for a string from the cursor position: /pattern Enter To quit: q Remarks : Review the first chapter for the classification of the manual into sections. The manual of the XENIX and SCO system differs from the normal manual layout described in the first chapter.

5.4

Display the current date and time : date

Syntax : date To show the current date and time, use the date command. System V based systems allow you to format the date and time display. e.g. the command: date +DATE: %d/%m/%y%nTIME: %H:%M:%S generates as output: DATE: 14/03/91 TIME: 14:45:05

ALCATEL UNIVERSITY

22

770 00440 0490-VHBE

COMMONLY USED UNIX COMMANDS

5.5

Display the calendar : cal

Syntax : cal [[month] year] The cal command can be used to display the calendar for a specified year or month of a year. Month can be ranging from 1 to 12, year can be ranging from 1 to 9999. cal 1992 cal 9 1752

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

770 00440 0490-VHBE

23

ALCATEL UNIVERSITY

COMMONLY USED UNIX COMMANDS

5.6

Get the terminals name : tty

Syntax : tty If you want to know the name of the terminal you are working with, enter the tty command. The result can be /dev/tty06. As you probably remember, this is a special file name corresponding to a (your) terminal.

5.7

Set the options of the terminal : stty

Syntax : stty [{option}] Use the stty command to see or change certain terminal options for the device currently coupled to standard input (for System V based systems) or standard output (for BSD based systems). Without options, the current terminal is used. The command stty -a displays the current settings. This command is also discussed in the chapter on SHELL scripts. Examples : stty erase ^H

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

The System V command stty -a < /dev/tty01 displays the current settings of the given terminal on stdout. In BSD, we should issue stty -a > /dev/tty01 The output will be displayed on stderr.

ALCATEL UNIVERSITY

24

770 00440 0490-VHBE

COMMONLY USED UNIX COMMANDS

5.8

List who is on the system : who

Syntax : who [am i] This command can be useful in order to know to which special file a user is connected (see output redirection). e.g. the command: who generates as output: fred tty03 feb 5 08:56 nick tty5c feb 5 09:03 cathy tty06 feb 5 11:23 If who am i is entered, the system will respond with your user name, terminal name and time of login.
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

On BSD based systems, it suffices to write any two arguments after who. e.g. The command who are you would give the same result as who am i Two other commands are available on SUN workstations : w finger Shows a list of who is logged in and what they are doing. Shows a list of who is logged in and displays for each user the comment field of the password file.

5.9

Log in as another user : su

Syntax : su [userName] This command makes it possible to log in without first logging out. Example : Suppose a user is working with user name paul. For some reason the user wants to log in with another user name (eg.pt84). He can do this by typing su pt84 Of course, he must give the correct password. After typing Ctrl-d the user paul can resume his work. The su command without option makes it possible to log in as super user (user name root).

770 00440 0490-VHBE

25

ALCATEL UNIVERSITY

COMMONLY USED UNIX COMMANDS

5.10 Change password : passwd Syntax : passwd After entering the command, the user will be asked for a new password. Some tips to find a safe password : Take at least 6 characters, Do not use words written in a dictionary Do not use a proper name Do not use telephone numbers
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

Make a combination of uppercase and lowercase characters Use punctuation marks : + - , ; . ! Use digits

Examples :

Cat+Dog C@t+D0g Apen93 tboNtb

ALCATEL UNIVERSITY

26

770 00440 0490-VHBE

COMMONLY USED UNIX COMMANDS

5.11 Change of group : newgrp Syntax : newgrp [groupname] The newgrp command changes the current group id of the user. Without argument, the group id is changed back to the original default group of the user. The default group can be found in /etc/passwd. The other groups which can be used by a specific user can be found in /etc/group.

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

770 00440 0490-VHBE

27

ALCATEL UNIVERSITY

COMMONLY USED UNIX COMMANDS

5.12 Information on the active processes : ps Syntax : ps [-{e|f}] [-u ulist] The ps command prints certain information on active processes. Without options, information is printed on processes associated with your current terminal. Options : -e : Gives information on all processes, and not only on the processes associated on your current terminal. -f :
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

Generates a full listing : UID, PID, PPID (parent PID), C (processor utilisation for scheduling), STIME (starting time), TTY, TIME (cumulative execution time for the process), COMMAND). -u : Only those processes are shown belonging to the given users in ulist. Examples : In order to get a full listing of all processes belonging to user aoss, issue: ps -ef -u aoss On BSD based systems, we must issue: ps -aux|grep aoss to obtain the same result. Look in the manual pages of your system to have an explanation of all possible options.

5.13 Terminate a process : kill Syntax : kill [-9] pid The kill command sends a signal to the process with the given process identification (pid). The default signal is number 15, which is the terminate signal. Only the super user can kill processes of other users. Examples : kill 4633 kill -9 4633 kill 0 Asks to terminate process 4633 (can be ignored). Terminates process 4633 (if it is yours). Asks to terminate all processes associated with the current terminal.

ALCATEL UNIVERSITY

28

770 00440 0490-VHBE

COMMONLY USED UNIX COMMANDS

kill -9 0

All processes associated with this terminal are killed (including the shell).

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

770 00440 0490-VHBE

29

ALCATEL UNIVERSITY

FILE MANIPULATION COMMANDS

6 FILE MANIPULATION COMMANDS


6.1 Print working directory : pwd

Syntax : pwd The pwd command displays the absolute path name of your working (current) directory. pwd is a valuable utility when moving around in the file system. (It is not uncommon to get lost in the file system.) 6.2
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

List the contents of a directory : ls

Syntax : ls [-{l|a|R|i|t|r}] [{fileName}] Use the ls command to list the file names in a directory. Display all files in the working directory : ls Display all files of the directory /bin : ls /bin Display all files of the directories /usr/rudy and /usr/bert : ls /usr/rudy /usr/bert Remark : To display the contents of a directory, the user must have read and execute (search) permission. Display all files in the current directory ending with .z. ls *.z Display all files in the current directory with file names starting with file and followed with one more character : ls file? Display all files matching a pattern : ls file[123456789] ls file[1-9] ls file[1-9a-z] ls le[a-kz]a Special symbols (wild cards) : * : Replaces any number of characters ? : Replaces one character

ALCATEL UNIVERSITY

30

770 00440 0490-VHBE

FILE MANIPULATION COMMANDS

[] : Replaces one character by one of the characters indicated within the square brackets. A minus sign within the square brackets is used to indicate a range of characters. Options : -a : Causes ls to display file names including those starting with a dot (e.g. .profile). -l : List in long format. You can see here : The file type. A -means an ordinary file A d means a directory file. An l means a symbolic link (see 3.5.2) A c means a character device (e.g. a terminal) A b means a block device (e.g. a disk) An s means a socket (TCP/IP networking) A p means a named pipe (inter-process communication) the protection mode of the file. first three positions : protection for the owner of the file second three positions : protection for members of the same group third three positions : protection for all other users the link count. the owner of the file. the group to which the file belongs. the size of the file, expressed in bytes. the date and time of last modification. -R : List all subdirectories recursively, so the current directory and all its subdirectories are listed. -i : Causes the ls command to display the file name and the inode number of the file. -t : sort by timestamp, default latest first. -r : reverse order for sorting Example: ls -lrt shows directory entries sorted by timestamp, oldest first.

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

770 00440 0490-VHBE

31

ALCATEL UNIVERSITY

FILE MANIPULATION COMMANDS

6.3

Change working directory : cd

Syntax : cd [directory] Use the cd command to change the current directory. If no argument is given, you will be returned to your home directory. You must have search (=execute, see file protection) permission for all directory names specified in the full pathname. cd cd cd cd cd cd /usr/christine/pascal/sources pascal/sources .. ../.. /

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

6.4

Make a directory : mkdir

Syntax : mkdir {directory} Use the mkdir command to create directories. The newly created directories are empty, except for the . and .. entries which are used by the UNIX system. To create a directory, you must have write access in the parent directory. mkdir textproc mkdir /rudy/general/textproc To create a directory in the home directory, and define it as working directory : cd;mkdir wp;cd wp In this last example, the semicolon ; is used to separate two commands : it is called the command separator (shell dependent).

6.5

Remove a directory : rmdir

Syntax : rmdir {directory} To delete a directory, use the rmdir command. You must have write access in the parent directory and the directory itself must be empty.

ALCATEL UNIVERSITY

32

770 00440 0490-VHBE

FILE MANIPULATION COMMANDS

rmdir textproc The rmdir command does not ask for confirmation. Another possibility to remove a directory is to use the rm -r command (see later). In this case, the directory must not be empty. No confirmation is asked, unless you specify the option -i. Note that rm -r is a very dangerous command!

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

770 00440 0490-VHBE

33

ALCATEL UNIVERSITY

FILE MANIPULATION COMMANDS

6.6

Determine nature of a file : file

Syntax : file fileName If you do not remember what kind of information is stored in a file, issue the file command. The file command guesses the kind of file. This is done by examining the file type (see ls -l command) to see if it is a directory, an ordinary file, or ... If the file seems to be an ordinary file, the execute bit of the protection mode is checked, followed by the contents of the file. Keep in mind that the file command can make mistakes ! file * output :
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

welcome bin hello hello.c

ascii text directory pure executable c program text

ALCATEL UNIVERSITY

34

770 00440 0490-VHBE

FILE MANIPULATION COMMANDS

6.7

Display the contents of a file

6.7.1 cat Syntax to display some file(s) : cat {fileName} The cat command reads each file and displays it on standard output (normally the screen). If no input file is given, cat reads from standard input (normally the keyboard). cat pascal/sources/a cat welcome byebye
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

If the output of the command is longer than one single screen, then it is possible to stop the scrolling by using Ctrl-S. By using Ctrl-Q, you are able to see the rest of the output. The cat command can be used to create a file. Therefore you need output redirection. This means that standard output is not coupled to the screen anymore but to a specified file. cat inFile > outFile In this example, the file inFile is not displayed on the screen but is written in the file outFile. outFile must be a non existent file. If not, the contents of the file will be replaced by the new contents. When writing cat > outFile the input will be taken from standard input (the keyboard). End the input with Ctrl-d (=End of File) on a new line. The cat command can also be used to append text to an existing file. Here too, we speak about output redirection : the text to display will not appear on the screen as usual, but will be written in a given file. cat cat cat cat welcome >> oldfile file1 file2 >> file3 f* >> oldfile >> file1

In this last example, the input must be given on the keyboard. Remark : The argument of the cat command may not be a binary file, otherwise your terminal may be blocked.

770 00440 0490-VHBE

35

ALCATEL UNIVERSITY

FILE MANIPULATION COMMANDS

6.7.2 Display a file one screen at a time : more Most of the UNIX systems support the commands more and/or pg (page). These commands can be used to display files one screen at a time. Syntax : more [+lineNumber] {fileName} pg [+lineNumber] {fileName} Example : By issuing the command more bigfile you can read the listing at your own speed. The first page is written on the screen. By typing: The Return or Enter key, you can see the next line A space, the next page is shown A q or Q, the more command is interrupted. A b or B you go back towards the beginning of the file A / you can specify a string to be searched When writing more +30 trala the contents of the file trala is displayed starting with line 30. When writing more the input for more is taken from standard input. Standard input is the keyboard. When writing cal 1994 | more the input for more is again taken from standard input, but here standard input is coupled to the standard output file of the cal command. So this means that the result of the cal command will not be written on the screen (as usual), but will be given as input for the more command. We say that the more command is an example of a filter.

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

ALCATEL UNIVERSITY

36

770 00440 0490-VHBE

FILE MANIPULATION COMMANDS

6.7.3 Display the end of a text file : tail Syntax : tail [+number|-number] fileName The tail command without any option shows the last 10 lines of the mentioned file. tail +30 bigfile skips the first 29 lines of the file. tail -30 bigfile shows the last 30 lines of the file.

6.7.4 Display the beginning of a text file : head Some UNIX systems (mainly the BSD based systems) support the head command to display only the beginning of one or more files. Syntax : head [-number] {fileName} The head command without any options shows the first 10 lines of the mentioned files. The option -n can be used to display the first n lines.

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

6.7.5 Display a file with pagination : pr Syntax : pr [options] {fileName} The pr command displays the file(s) page per page. Each page has a header containing the name of the file, the page number and the date of last modification. pr -h Booking information bkinfo pr -l48 file1 The option -h indicates that the next argument must be the header instead of the file name. The option -l48 indicates that the length of each page must be 48 instead of the default of the system. Consult the manual of your computer system to know other interesting options of the pr command.

770 00440 0490-VHBE

37

ALCATEL UNIVERSITY

FILE MANIPULATION COMMANDS

6.8

Print files : lp

Syntax : lp [-d printerName] [{file}] Use the lp command to print one or more files on a printer. All command output can be printed by using the piping mechanism. Examples : To print the calendar of the year 2000 : cal 2000|lp In this example, the standard output of the cal command is coupled to the standard input of the lp command. This means that the output of the cal command is used as input for the lp command. To print a file with pagination and a specific header : pr -h This is a new header file2|lp The output of the pr command is not shown on the screen, but will be used as input for the lp command. To send the output to a certain printer, use the option d. To list the names of the available printers, use the command lpstat -v To see the situation of the print queue, use command lpstat. To kill a print job, use command lprm jobNumber

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

6.9

The a2ps utility

a2ps is a GNU (Free Software Foundation) utility (so it is not part of standard UNIX) that formats files for printing on a PostScript printer. The format used is nice and compact: normally two pages on each physical page, borders surrounding pages, headers with useful information (page number, printing date, file name or supplied header), line numbering, pretty-printing (interpret the text for certain programming languages so that elements of different language element types (keywords, comments, ) can be printed in different styles to make the printout more readable), symbol substitution etc. This is very useful for making archive listings of programs or just to check your code in the bus. We describe here the latest version (4th of march 1999) of a2ps, version 4.12.

ALCATEL UNIVERSITY

38

770 00440 0490-VHBE

FILE MANIPULATION COMMANDS

Syntax: a2ps [options] [{file}] Note: in fact files and options can be mixed on the command line, so you can type: a2ps -q myfile as well as a2ps myfile -q If no files are given, a2ps prints its standard input. If - appears in the files, it designates the standard input too. To get the version you are using type: a2ps -V (or a2ps --version) To get a reminder list of options type: a2ps -h (or a2ps --help)
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

To get a reminder of the default settings type: a2ps -list=defaults Some of the most important default settings in a2ps: Sheets: default paper = A4 layout per page = 2 x 1 (landscape, rows first) borders = yes compact mode = no inside margin =0 Virtual pages: number lines = no format = 80 characters per line tabulation size =8 non printable format = caret (i.e., ^C, M-^C etc.) Input: truncate lines = no interpret = yes end of line = any type default encoding = ISO-8859-1 default prologue = bw delegating = yes (a2ps will use other utilities (delegate part of the job to be done)) Pretty-printing: style sheet = selected automatically (for the programming language) highlight level = normal Output: destination = sent to the default printer

770 00440 0490-VHBE

39

ALCATEL UNIVERSITY

FILE MANIPULATION COMMANDS

Some of the most important options: The order between options does matter, especially between options that influence the same parameters. For instance, a2ps -1 -l132 (-1: see below; -l: set the number of chars per line) is not the same as a2ps -l132 -1 (the latter being equivalent to a2ps -1). Option: -v[level] or --verbose[=level] Tell what we are doing. At level: 0: report nothing. 1: a2ps just prints the total number of pages printed. 2: (default), it reports the number of pages for each file. above: it gives internal details. Option: -M medium or --medium=medium Typical values for medium are A3|A4|A5|B4|B5|Letter|Legal A4dj and Letterdj are also defined for Desk Jet owners, since that printer needs bigger margins. Option: -r or --landscape : print in landscape mode Option: -R or --portrait : print in portrait mode Option: --columns=num : specify num columns of virtual pages per physical page. Option: --rows=num : specify num rows of virtual pages per physical page. Option: --major=direction : specify whether the virtual pages should be first filled in rows (direction : rows) or in columns (direction : columns). Option: -1 : 1 x 1 portrait, 80 chars/line, major rows i.e. alias for:
--columns=1 --rows=1 --portrait --chars-per-line=80 --major=rows.

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

Option: -2 : 2 x 1 landscape, 80 chars/line, major rows. Option: -3 : 3 x 1 landscape, 80 chars/line, major rows. Option: -4 : 2 x 2 portrait, 80 chars/line, major rows. Option: -5 : 5 x 1 landscape, 80 chars/line, major rows. Option: -6 : 3 x 2 landscape, 80 chars/line, major rows. Option: -7 : 7 x 1 landscape, 80 chars/line, major rows. Option: -8 : 4 x 2 landscape, 80 chars/line, major rows. Option: -9 : 3 x 3 portrait, 80 chars/line, major rows. Option: -P name or --printer=name : send output to printer name.

ALCATEL UNIVERSITY

40

770 00440 0490-VHBE

FILE MANIPULATION COMMANDS

For more detailed information see the manual for version 4.12 at the URL: http://www-inf.enst.fr/~demaille/a2ps/doc-4.12/a2ps_toc.html

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

770 00440 0490-VHBE

41

ALCATEL UNIVERSITY

FILE MANIPULATION COMMANDS

6.10 Copy a file : cp Syntax : cp sourceFile destinationFile cp {sourceFile} directory

Use the cp command to make a copy of a file. The user must have read access for the files to be copied. First possibility : sourceFile will be copied to destinationFile. If destinationFile already exists, then the user must have write access to it. If so, its contents are erased and the contents of sourceFile are written in destinationFile.
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

Second possibility : If the last argument is a directory, all preceding arguments (files) are copied into it.

6.11 Move a file : mv Syntax : mv sourceFile destinationFile mv {sourceFile} directory

The mv command can be used to : Move one or more files from one directory to another mv /usr/bert/pascal/exer /usr/christine/pascal/sources (the user must have write permission in the directory /usr/christine/pascal/sources) Rename a file mv oldname newname

ALCATEL UNIVERSITY

42

770 00440 0490-VHBE

FILE MANIPULATION COMMANDS

6.12 Remove a file : rm Syntax : rm [-{r|i|f}] {fileName} Use the rm command to delete one or more files. rm /usr/user2/test When deleting more than one file, it can be useful to use the option -i (interactive). This means that rm asks whether to delete each file or not. So the command rm -i * is a safer way to delete multiple files than the command rm *.
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

As we have seen before, to delete a directory one can issue the rmdir command. The disadvantage of this command is that the directory must be empty. An easier way to delete a directory is issuing the command. rm -ri {dirname} The option -ri deletes recursively and interactively the entire contents of the directory followed by the directory itself. To delete a file, the user does not need to have write access for the file itself : the removal of a file means not to write in the file, but to remove the name of the file in the directory where it is placed in. So to delete the file, one must have write (and search) access in the directory instead of in the file. The option -f (force) prevents the system asking for confirmation when the user has no write access for the file.

770 00440 0490-VHBE

43

ALCATEL UNIVERSITY

FILE MANIPULATION COMMANDS

6.13 Sorting input : sort Syntax : sort [-{d|b|f|n|r|t|x|u}] [+pos1] [-pos2] [-o file] {file} A simple form of the sort command is : sort file. The contents of the file will be sorted alphabetically and the result will be written on standard output. If no file is given, the lines entered on standard input will be sorted. To write the result in a file use the -o option or output redirection. Normally, sorting starts from position 1 to the end of the line. +pos1 indicates the begin position of the sorting. -pos2 indicates the first position not to be sorted anymore.
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

pos1 and pos2 have the following format : n.m n indicates the numbers of fields to skip. m indicates the number of characters to skip within the next field. Fields are separated with one blank unless otherwise specified (-tx option). Options : d : Sort in dictionary order : only letters, digits and blanks count. b : Ignore leading blanks and tabs in comparisons. f : Ignore distinction between uppercase and lowercase letters (fold). n : If sorting field begins with a digit, sorting is done by arithmetic value. r : Reverse order of sort. tx: Character x is used as field separator. u : Eliminate duplicate lines in sorted output (unique).

Some examples : sort +1.0 teachers Sorting starts from the second field till the end of the line. sort -1.0 teachers Sorting starts on position 1 and ends on the end of the first field. sort +2.0 -3.0 teachers The lines will be sorted on the third field. sort +2.0 -3.0 +1.0 -2.0 teachers

ALCATEL UNIVERSITY

44

770 00440 0490-VHBE

FILE MANIPULATION COMMANDS

More than one sort field can be given.

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

770 00440 0490-VHBE

45

ALCATEL UNIVERSITY

FILE MANIPULATION COMMANDS

6.14 Report the differences between files : diff Syntax : diff file1 file2 The diff command compares two text files and looks line per line for the differences. Determines what changes must be made in order to equalise the two files. Example :

Suppose that the contents of file1 is :

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

*********************************************************** Please take care to leave the room in good repair after the lesson. - Chairs in place - Clean tables - ... Thanks.

Suppose that the contents of file2 is :


Please take care to leave the room in good repair after the lesson. - Chairs in place - Clean tables - Greenboards washed - Whiteboards wiped - ... Thanks.

When issuing the command : diff file1 file2

ALCATEL UNIVERSITY

46

770 00440 0490-VHBE

FILE MANIPULATION COMMANDS

The result will be :


1c1 < ********************************************************* --> 4a5,6 > - Greenboards washed > - Whiteboards wiped 6,7d7 < <

This means : Change (c) line 1 of the first file (1c) to line 1 of the second file (1c1). The line following a < is a line of the first file. The line following a > is a line of the second file. Append (a) after line 4 of of the first file (4a) lines 5 and 6 of the second file (4a5,6). Delete lines 6 and 7 of the first file.

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

770 00440 0490-VHBE

47

ALCATEL UNIVERSITY

FILE MANIPULATION COMMANDS

6.15 Display common lines in two sorted files : comm Syntax : comm [-{1|2|3}] file1 file2 Use the comm command to display all common lines of two sorted files. Normally, the output is displayed in three columns: column 1 : lines that are unique to the first file, column 2 : lines that are unique to the second file, and column 3 : lines that are common to both files. By using options, it is possible to suppress the output of one or more columns. e.g. the option -12 would only display the output of the third column (that is to say the common lines).
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

A file name equal to - means standard input, e.g.: sort file1 > f1 sort file2 | comm f1 -

ALCATEL UNIVERSITY

48

770 00440 0490-VHBE

FILE MANIPULATION COMMANDS

6.16 Joining two files : join Syntax : join [options] file1 file2 The join command is used for combining two files by looking to the contents of a common field. The files must be sorted on this common field. The output of the command is written on standard output. Options : -jm n To define the common field : the n-th field of the m-th file, e.g.: -j1 3 -j2 6 means : the third field of the first file, the sixth field of the second file. To define the fields which must be displayed in the output.: m.n means the n-th field of the m-th file. The fields are separated by the character C. All lines of file m (1 or 2) which can not be joined with the other file are also given in the result.

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

-o {m.n}

-tC -am

Example : Contents of file1 : Arnold Leo Marc Willem Contents of file2 : Armand Dewilde employee Sidmar Arnold Dekoninck driver Kredietbank Brigitte Gheeraert designer Benetton Leo Vermeiren doctor UZ Marc Debacker teacher BEC Stan Vercammen projectleader BEC join -j1 1 -j2 1 -o 2.2 2.1 1.2 2.3 2.4 file1 file2 The result will be: Dekoninck Arnold - driver Kredietbank Vermeiren Leo - doctor UZ

770 00440 0490-VHBE

49

ALCATEL UNIVERSITY

FILE MANIPULATION COMMANDS

Debacker Marc - teacher BEC

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

ALCATEL UNIVERSITY

50

770 00440 0490-VHBE

FILE MANIPULATION COMMANDS

6.17 Search a file for a pattern : grep Syntax : grep [options] pattern [{file}] The grep utility searches in the given file(s) for lines containing the pattern. The lines found are displayed on standard output. If no files are given, the input will be taken from standard input. Options : -n : each line is preceded by its line number. -c : only the number of lines found is displayed. -v : displays all lines except those containing the pattern. -l : displays only the names of files containing the pattern. -i : case insensitive. Examples : grep circular lists file? grep -l Mr. Lee *

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

770 00440 0490-VHBE

51

ALCATEL UNIVERSITY

FILE MANIPULATION COMMANDS

6.18 Remove adjacent repeated lines in a sorted file : uniq Syntax : uniq [-{u|d|c}] [+n] [-n] [input [output]] The uniq command compares adjacent lines of the sorted input file and removes lines in a way that there remains only one copy of each different line. Options : -u -d -c
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

+n -n

The lines which appear only once are given. One copy of just the repeated lines are given. Each line in the output is preceded by the number of times the line occurred in the input. This option may not be combined with -u or -d. The first n characters are ignored. The first n fields are ignored. Fields are skipped before characters.

ALCATEL UNIVERSITY

52

770 00440 0490-VHBE

FILE MANIPULATION COMMANDS

6.19 Translate characters : tr Syntax : tr [-{c|d|s}] string1 [string2] This command is useful to change the characters mentioned in string1 of standard input into the characters mentioned in string2. The result is written on standard output. Example : tr AB ab < file1 > file2 will change any A of file1 to a, and any B to b. The result is written in file2.
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

Options : -c -s -d All characters but those of string1 are changed. Repeated characters in the output are reduced to only one single character. The characters of string1 are deleted.

Example : tr -cs [A-Z][a-z] \012 < filein > fileout tr -d abc

770 00440 0490-VHBE

53

ALCATEL UNIVERSITY

FILE MANIPULATION COMMANDS

6.20 Word count : wc Syntax : wc [-{c|w|l}] [{file}] This command counts the number of characters, words and lines in the mentioned file(s) or in the standard input if no file is given. If more than one file is given, the wc command also keeps a total count. Options : -w -c
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

counts only the number of words counts only the number of characters counts only the number of lines

-l

ALCATEL UNIVERSITY

54

770 00440 0490-VHBE

FILE MANIPULATION COMMANDS

6.21 Compressing files : pack Syntax : pack {file} In most cases, the contents of the file will be saved in a packed format. In this way, the file occupies less memory space. The name of the packed file is file.z and the original file name disappeared. No packing will occur if: the file appears to be already packed the file name has more than 12 characters (only for old SV) the file has links no disk space will be saved after the packing
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

The saved space depends on the size and the character distribution of the file. (The packing is done using the Huffman algorithm.) A packed file can be displayed on standard output using the pcat command. Syntax : pcat {file} To expand the packed file again, use the unpack command : Syntax : unpack {file} The unpack command fails when: the file was not packed the file name already exists the file can not be created fo some reason.

770 00440 0490-VHBE

55

ALCATEL UNIVERSITY

FILE MANIPULATION COMMANDS

6.22 Display file in octal format : od Syntax : od [-{c|b|d}] [file] Without option, the od command displays the contents of the file in octal. Using an option, the file is displayed in a format of your choice. Options : -o -b -d
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

interprets words in octal (default). interprets bytes in octal. interprets words in decimal. interprets words in hex. interprets bytes in ASCII. Non displayable characters will be displayed in a C notation (e.g. \t = tab, \n = newline) or by \ followed by three octal digits.

-x -c

Certainly, there are also other options available on your system. Therefore we refer to your reference guide (because they are implementation dependent). The output format is not standardised.

ALCATEL UNIVERSITY

56

770 00440 0490-VHBE

FILE MANIPULATION COMMANDS

6.23 Finding files : find Syntax : find directory-list condition-list action-list The find command searches each directory in the directory-list (and all of its subdirectories) in order to locate the files that meet the criteria in the condition-list. The action list is performed on each located file. Condition-list items : -name filename true if the last component of pathname matches the given filename. true if the permission of the file matches mode. true if the file has n links. true if the i-node number of the file is n. true if the file was modified in the last n days. A + in front of a number means greater than. A - in front of a number means less than.

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

-perm mode -links n -inum n -mtime [+|-]n

The following operators can be used : !: not -a : and -o : or ( ) : grouping Action-list items : -print -exec command displays the pathname. executes the command. If the argument of the command is {}, the argument will be replaced with the pathname of any located file. When the braces are used, the command must end with \; or ;

Examples : find find find find . . . . -name groen -print ( -name *.o -o -name *.c ) -print ! -user wlan -print -atime +100 -exec rm -i {} ;

770 00440 0490-VHBE

57

ALCATEL UNIVERSITY

FILE MANIPULATION COMMANDS

find / -inum 2919 -print

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

ALCATEL UNIVERSITY

58

770 00440 0490-VHBE

FILE MANIPULATION COMMANDS

6.24 Change ownership of file : chown and chgrp Syntax : chown owner file chgrp group file

There are 2 commands for changing ownership. The chown command is used to change individual ownership of a file. The chgrp command is used to change the group ownership of a file. Owner and group may be specified by name or by number.
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

Only the owner (and the root) can change the ownership of the file.

6.25 Command df One of the biggest and most frequent problems that systems have is running out of disk space. The df command with the -k option shows the free disk space on each disk that is mounted. It displays the following information (Example: typical case) df -k Filesystem /dev/dsk/c0t0d0s0 /dev/dsk/c0t0d0s6 swap /dev/dsk/c0t0d0s7 /dev/dsk/c0t0d0s5 gs:/home/prog/met kbytes: used: avail: capacity: Mounted on: kbytes used 38111 21173 246167 171869 860848 632 188247 90189 492351 179384 77863 47127 avail 13128 49688 860216 79238 263737 22956 capacity 62% 78% 0% 53% 40% 67% Mounted on / /usr /tmp /home /opt /home/met

Total size of usable space in file system (in kbytes) Space used (in kbytes) Space available for use (in kbytes) Percentage of total capacity used Mount point

770 00440 0490-VHBE

59

ALCATEL UNIVERSITY

FILE MANIPULATION COMMANDS

6.26 Command touch The touch command can be used for a number of purposes depending on whether a file already exists. If a file does not exist, the touch command will create it if you have write access to the directory. If a file is already present, the touch command modifies the last modification time of the file.

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

ALCATEL UNIVERSITY

60

770 00440 0490-VHBE

FILE PROTECTION

7 FILE PROTECTION
7.1 Introduction

There are three different classes of file users : the owner of the file. Generally, this is the creator of the file. the users belonging to the same group. all other users.
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

There are three ways for accessing a file : read, write, execute. The meaning of these modes is different for ordinary files than for directories : ordinary files : read: allows reading of file contents, write: allows changing of file contents, execute: allows executing the file as a command. directory files : read: allows listing of files within the directory (e.g. use of ls command), write: allows creation of new files and removing old ones, execute: (search) allows accessing the files named in that directory. To see the protection mode of an existing file, use the ls -l command. 7.2 Changing the protection bits for files to be created

Introduction When creating a file, a protection mode is given to it. This protection mode is determined by the default protection mode and by the umask value. The default protection mode is generally equal to the octal values : 777 for directories and compiled files, 666 for text files. The first digit is the protection for the owner, the second for the group, and the third one for the others. 7 means read, write and execute access. 6 means read and write access. This is because the value of the read bit is 4, the value of the write bit is 2 and the value of the execute bit is 1.

ALCATEL UNIVERSITY

62

770 00440 0490-VHBE

FILE PROTECTION

read access: write access: execute access:

4 or binary 100 2 or binary 010 1 or binary 001

The real protection mode for files to be created depends on the default protection mode and on the umask value (user mask). The default umask value is generally 022 (binary 000 010 010). Each user can change his own umask value using the umask command. protection mode = default protection mode AND (NOT umask value)
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

So, the protection mode for directories and compiled files to be created is 755. Calculation : (111 111 111) and not (000 010 010) = 111 101 101. The protection mode for newly created ascii files is 644. Calculation : (110 110 110) and not (000 010 010) = 110 100 100.

The umask command Syntax : umask [value] The umask command without any argument shows the current setting of the umask value. Use the umask command with an argument to change the umask value. value is the desired umask value represented in octal digits. It is useful to write this command in the start up file, since otherwise its value only remains in effect until the end of the session.

770 00440 0490-VHBE

63

ALCATEL UNIVERSITY

FILE PROTECTION

7.3

Changing the protection bits of existing files

Once a file has been created, the owner of the file can change the protection mode by using the chmod command. Two different formats can be used : 1st possibility : Syntax : chmod mode {file} mode are three octal digits, representing the access privileges for the owner, the group and the others. As we have seen before, the octal values for read, write and execute are 4, 2 and 1.
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

chmod 640 test

2nd possibility : Syntax : chmod abc[{,abc}] [{file}] a determines to who the change is applicable. It must be replaced by : u g o a (user) (group) (others) (all) in case it is a change for the owner of the file, in case it is a change for the members of the same group, in case it is a change for the users of another group, or in case it is a change for all users.

b determines the operation code. It must be replaced by : + = to add a permission, to remove a permission, or to replace the existing permission by a new one.

c shows if it concerns reading (r) or writing(w) or executing (x) or any combination. If c is omitted, all permissions are disabled. Examples : chmod u=rwx testfile chmod u+x,g=,o= file1 file2 In the first example, the owner of the file testfile has from now on all permissions, and the permissions for all other users remains unchanged.

ALCATEL UNIVERSITY

64

770 00440 0490-VHBE

FILE PROTECTION

In the second example, the owner of the file file1 and file2 has from now on also execute access, and all other users have no access anymore.

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

770 00440 0490-VHBE

65

ALCATEL UNIVERSITY

COMMUNICATION UTILITIES

8 COMMUNICATION UTILITIES
8.1 The write utility

The write utility can be used to send a message to another user. Syntax : write user [ttyDevice]

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

Example : After user bert has entered write annie user annie is notified of the message by a sentence as Message from bert tty5b ... User bert now enters his message and ends it by pressing Ctrl-d. In the meanwhile user annie can see the message appearing on the screen. Remarks : 1. Specifying the tty device number can be useful if the user is logged in on more than one terminal. 2. The receiver can deny messages sent to the screen by the mesg command : mesg reports the current state mesg n forbids messages mesg y permits messages

8.2

The talk utility

On some systems (eg. SUN), the talk utility can be used to talk to another user. Both users must be logged in. Syntax : talk user@node [ttyDevice] To answer the person who wants to talk to you, enter the same command as above. Both users now can communicate with each other. Use the interrupt key (Ctrl-c) to stop the conversation. Same remarks as for the write utility.

ALCATEL UNIVERSITY

66

770 00440 0490-VHBE

COMMUNICATION UTILITIES

8.3

The mail utility

The mail command can be used to send or read electronic mail. Sending mail : Syntax : mail {user} The mail message will be read from standard input. Type Ctrl-d on a new line to finish the message: the message is sent to the other user(s).
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

Syntax : mail {user} < file The file will be sent.

Reading mail : Just enter the mail utility and you get an overview of the messages in your mailbox. Select the message you want to read by typing the message number, or press return to get the messages one by one. The following commands can be issued in the mail utility : p d d2 help m {user} reply s file w file ! command q print, shows the last message once again, deletes the last message read, deletes message number 2, overview of all mail commands, the message last read is sent to the given users, to reply to the message, saves the message in the file, writes the message without header in the file, to execute a UNIX command, quit

770 00440 0490-VHBE

67

ALCATEL UNIVERSITY

THE vi EDITOR

9 THE vi EDITOR

9.1

Introduction

The vi editor is a screen editor available on every UNIX system. It is possible to work in command mode or in text entry mode :

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

vi ----------> SHELL <---------ZZ

vi command mode

a, i, c, o, s -------------> <-----------Esc

vi text entry mode

vi [file] :q :q! ZZ :wq :w file :w

start the edit session exit the edit session, no changes are made exit the edit session, changes are not saved exit the edit session, changes are saved same as ZZ write the edit buffer to another file write the edit buffer to the file you are editing

ALCATEL UNIVERSITY

68

770 00440 0490-VHBE

THE vi EDITOR

9.2

Cursor movements

arrowKeys nh nj nk nl b nb e ne
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

move n positions to the left (default 1) move n lines down (default 1) move n lines up (default 1) move n positions to the right (default 1) move to begin current (or previous) word move to begin n words ago move to end current (or next) word move to end n words further on move to begin current (or previous) sentence move to end current (or next) sentence move to first position of screen move to last position of screen move to first position of the line in the middle of the screen move to first non blank character of line move to last non blank character of line move to first position of line

( ) H L M ^ $ 0

9.3

Screen movements scroll 12 lines down scroll 12 lines up scroll 1 screen forward scroll 1 screen backward scroll 1 line down scroll 1 line up scroll to first position of last line scroll to n-th line of file

Ctrl-d Ctrl-u Ctrl-f Ctrl-b Ctrl-e Ctrl-y G nG

Note : A sentence is terminated by ., ! or ?, followed by two spaces.

770 00440 0490-VHBE

69

ALCATEL UNIVERSITY

THE vi EDITOR

9.4 i I a A o O

Inserting text insert before cursor position insert before begin of line insert after cursor position insert after end of line insert after current line insert before current line

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

9.5 x dd ndd dw ndw d$ d^ d) d(

Deleting text delete current character delete current line delete n lines delete current word delete n words delete to end of line delete from beginning of line delete to end of sentence delete from beginning of sentence

9.6 cw c$ c) c( r s R

Replacing text replace to end of current word

replace current character by one single character replace current character by text replace existing text by new text (replace mode)

ALCATEL UNIVERSITY

70

770 00440 0490-VHBE

THE vi EDITOR

9.7

Search commands search from cursor position to end of file search from cursor position to top of file find next occurrence find next occurrence in other direction

/string ?string n | // | ?? N /^string /string$ /^string$


2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

undo last search request

9.8

Moving text

1. Use the delete command to store text in an (unnamed) buffer. 2. Reposition the cursor. 3. Get text out of the buffer : p the text is placed after the current position. P the text is placed before the current position.

9.9

Copying text

1. Use the yank command to store text in an (unnamed) buffer. 2. Reposition the cursor. 3. Get text out of the buffer : p the text is placed after the current position. P the text is placed before the current position.

9.10 Joining lines 1. Position cursor on the first line to be joined. 2. Use J to join the current line and the next one, or use nJ to join the current line and the n-1 following lines.

770 00440 0490-VHBE

71

ALCATEL UNIVERSITY

THE vi EDITOR

9.11 Executing a shell command :!command

9.12 Other interesting commands u Ctrl-L :nr file


2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

undo last command refresh screen the mentioned file will be copied after line n to see the line number in front of each line opposite of :set number

:set number :set nonumber Remark :

It can be useful to place the set number command in the .exrc file. This is a file which will automatically be executed when starting the vi editor. The .exrc file must be stored in the home directory.

ALCATEL UNIVERSITY

72

770 00440 0490-VHBE

SHELL SCRIPTS

10SHELL SCRIPTS
A shell script is a file containing UNIX commands. When executing the file, all commands within the file will be executed sequentially. (compare with. batch files in MSDOS, command procedures in VAX/VMS)

Remark : When writing a shell script, use the Bourne shell or the Korn shell instead of the C shell. These shells have a lot more facilities for shell programming than the C shell. The commands explained in this chapter are based on the Korn shell.

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

10.1 How to execute a shell script ? There are different ways to execute a shell script : sh filename filename The difference between these two ways is that in the first case the file must not be executable (x-bit must not be set in the protection code). Other possibilities are : using the at command, e.g.: at 1530 jan 19 filename at 9 friday filename filename & the file will immediately be executed in the background Input and/or output redirection is necessary to prevent input and output from the keyboard/screen. nohup filename & the file will immediately be executed in the background, and the execution continues even after logging off from the terminal. No output redirection is necessary : standard output and standard error are coupled to the file nohup.out in the current directory. If nohup.out can not be created in this directory (because of write protection), it will be created in the HOMEdirectory. nohup means no hang up.

ALCATEL UNIVERSITY

74

770 00440 0490-VHBE

SHELL SCRIPTS

10.2 SHELL variables A shell variable name begins with a letter (upper or lowercase) or underscore character and optionally is followed by a sequence of letters, underscore characters or numeric characters. A shell variable must not be declared before using it. Unlike other programming languages, there is no type associated with a shell variable. Every value that you assign to a variable is simply treated as a string of characters by the shell. For example: fruit=apple The variable fruit is assigned the value apple. Note that embedded spaces are not allowed either before or after the equal sign. To access the assigned value, you must immediately precede the name of the variable by a dollar sign, e.g.: echo $fruit echoes the contents of the variable fruit on standard output. The value of a shell variable can be assigned to another shell variable in the expected fashion , e.g.: file=memo save_file=$file echo $save_file displays: memo.

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

Its generally a good idea to use meaningful variable names. This makes your shell scripts more understandable. Use the set command without option to obtain a list of all defined shell variables in the current environment. Use the unset command to clear the definition of the variable. eg.: unset save_file

770 00440 0490-VHBE

75

ALCATEL UNIVERSITY

SHELL SCRIPTS

10.3 Exporting variables Whenever you execute a shell script, the shell creates an entirely separate environment for that script to run in. This means that the script gets its own distinct set of variables. Any nonexported variables that you assigned values to before executing the script cannot be accessed or changed in the script. Example : Suppose the contents of the executable file foo is : echo :$x: x=50 echo :$x: Look at the output of the following commands : $ x=100 $ echo $x 100 $ foo :: :50: $ echo $x 100 $ An exported variable is accessible to subsequently executed programs, but if a program wants to change the variable, the changes are not known on the higher level. Example : Suppose the contents of the executable file foo is : echo :$x: x=50 echo :$x: Look again at the output of the following commands : $ x=100 $ export x $ echo $x 100 $ foo :100: :50: $ echo $x 100 $

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

ALCATEL UNIVERSITY

76

770 00440 0490-VHBE

SHELL SCRIPTS

10.4 Positional parameters scriptFilename par1 par2 par3 par3 par4 par5 par6 par7 par9 par1 is saved in $1 par2 is saved in $2 par3 is saved in $3 . . par9 is saved in $9 scriptFilename is saved in $0 Although more than nine parameters can be given, there exist only nine positional parameter variables ($1 to $9) in the Bourne shell. The Korn shell supports a lot more positional parameter variables. A positional parameter of more than one digit must be enclosed in braces (e.g. ${10}).
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

$# contains the number of arguments passed to the shell script. $* contains all arguments that were passed. shift shifts all positional parameters one position to the left.

Example Contents of the file reverse : echo $3 $2 $1 echo the number of given parameters is $# echo they are $* shift echo $1 $* echo the program is called $0 If the program is called by: sh reverse Ann Steve Bert Carl Gwen Jos cat dog lion bird then the output will be as follows: Bert Steve Ann the number of given parameters is 10 they are Ann Steve Bert Carl Gwen Jos cat dog lion bird Steve Steve Bert Carl Gwen Jos cat dog lion bird the program is called reverse It is possible to give the positional parameters a value in the shell script itself. This is done by means of the set command. Example:

770 00440 0490-VHBE

77

ALCATEL UNIVERSITY

SHELL SCRIPTS

set wine water $1 will contain the value wine $2 will contain the value water The other positional parameters are unset. 10.5 Interactive input By using the read instruction it is possible to assign a value to a shell variable in an interactive way. Example: echo Enter three words : read word1 word2 word3 The user must write his answer on one line. The first value entered will be stored in word1, the second in word2 and the rest will be stored in word3.
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

By using \c (only System V), the position of the cursor is saved. This means that the user can enter his answer immediately after the echoed string, e.g.: echo Enter three words : \c read word1 word2 word3 (BSD based systems : echo -n Enter three words :) Other special characters (only System V) which can be used in the echo command are : \n : newline \t : tab \b : backspace

10.6 Comments When your shell script is rather complicated, it is a good idea to write comments wherever it is needed for clearness. Everything you write after # and until the end of the line is interpreted as comments.

10.7 Simple calculations : expr To make some simple calculations, the expr command can be used.

ALCATEL UNIVERSITY

78

770 00440 0490-VHBE

SHELL SCRIPTS

The expr command needs some arguments which form an arithmetic expression. The result of this arithmetic expression is written to standard output (normally the screen) or can be used in another command, e.g.: expr 12 - 7 echo The result of the addition is expr 3 + 5 int1=expr 7 \* 6 Sometimes the backslash \ must be used to avoid the shell interpreting special symbols like * (wild carding). Following operators can be used within the expr command : + addition - subtraction * multiplication / division % modulo
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

770 00440 0490-VHBE

79

ALCATEL UNIVERSITY

SHELL SCRIPTS

10.8 if and test instruction Syntax of the if instruction : if commands then commands fi if commands then commands else commands fi

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

if commands then commands elif commands then commands fi

if commands then commands elif commands then commands else commands fi

As you can see, if must be followed by one or more Unix commands. The return code of the last command is used to know whether the then branch or the else branch (if present) must be executed. If return code = 0, the then branch is executed. If return code <> 0, the else or elif branch is executed. A return code equal to zero means by convention that the command is ended well. Example : if grep UNIX $1 > /dev/null then echo $1 contains the word UNIX else echo $1 does not contain the word UNIX fi

ALCATEL UNIVERSITY

80

770 00440 0490-VHBE

SHELL SCRIPTS

In order to test a classic condition in the if statement, use the test command : Syntax of the test instruction : test expression or [ expression ] where expression can be: -r file to test if the file is readable -w file writable -x file executable -f file not a directory and exists -d file a directory -s file exists and size > 0 -z string the length of the string = 0 -n string >0 string1 = string2 two strings are identical string1 != string2 two strings are not identical n1 -equation n2 to compare two integers equation can be eq, ne, gt, lt, ge, or le Combinations can be made by -a (logical AND), -o (logical OR) and ! (logical NOT). Use \( and \) to group. When the value of the expression is true, the test command returns a zero exit status.

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

Examples : if test $# -ne 2 then echo This instruction requires two arguments fi if [ -d /usr/wlan/c -a -w /usr/wlan/c ] then vi /usr/wlan/c/pgm fi

770 00440 0490-VHBE

81

ALCATEL UNIVERSITY

SHELL SCRIPTS

10.9 case instruction Syntax : case variable in {pattern) esac The contents of the variable is evaluated. If the contents matches a pattern, the instruction(s) belonging to this pattern is (are) executed and following patterns are not taken into account.
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

[{instruction;}] instruction;;}

If the contents of the variable does not match any pattern, execution continues after esac. The number of patterns and instructions per pattern is arbitrary. Every instruction must end with a semicolon. Instructions belonging to one pattern must end with an additional semicolon. So, two semicolons after each other means : execution continues after esac. Example : case $1 in *.c) cc $1;; *.h | *.pas ) ;; *) echo type of $1 is unknown;; esac

ALCATEL UNIVERSITY

82

770 00440 0490-VHBE

SHELL SCRIPTS

10.10 Syntax :

for instruction

for variable in {word} do {instruction} done During the first execution of the loop, variable is set to word1. During the second iteration, variable is equal to word2. So this means that the instruction(s) in the body of the loop is (are) executed as many times as there are words. for variable do {instruction} done When the variable is not followed by a number of words, the variable is subsequently set to all the positional parameters. Examples : for cfile in alpha beta gamma do cat $cfile.c # or : cat ${cfile}.c done for i in * do echo $i done

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

Remark : break can be used within the body of the loop in order to exit the loop immediately. continue can be used within the body of the loop in order to continue immediately with the next iteration.

770 00440 0490-VHBE

83

ALCATEL UNIVERSITY

SHELL SCRIPTS

10.11 Syntax :

while instruction

while commands do {instruction} done Commands are executed before every possible iteration of the loop. The loop will be executed when the return code of the last command is zero. The commands are executed once again, and from the moment the return code is different from zero, execution continues after done. Same remark as with the for instruction.
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

10.12

true command

The true command does nothing except return with a zero exit value. Using the true command, it is possible to program an endless loop. while true do {instruction} done

10.13

sleep instruction

The sleep instruction can be used to delay a process for a number of seconds. eg. sleep 30 delays the process for 30 seconds. The maximum number of seconds is system dependent.

ALCATEL UNIVERSITY

84

770 00440 0490-VHBE

SHELL SCRIPTS

10.14

exit command

Normally, the execution of a shell script ends at the end of the file. The execution can end earlier when executing the exit command. Syntax : exit [exitCode] Executing exit without argument terminates the process immediately returning the value (exit code, return code) zero to the higher level (parent process). Executing exit n where n is a positive integer terminates the process returning the exit code n to the parent process. The parent process can use this exit code either in an if or while statement, or using the variable $?. $? is a variable containing the exit (return) code of the last executed command.
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

10.15

Echo text on standard output

All arguments of the echo command are displayed on standard output. Quotes (single or double) must be used in order to keep the number of blanks written between the arguments, e.g.: echo column1 column2 will result in : column1 column2 echo column1 will result in : column1 column2 column2

On System V based systems, special characters can be used in the echo command : \c : save the cursor position \t : tabulation character \n : new line \b : backspace These special characters must be written within single or double quotes. Other examples : echo Enter your choice : echo \t\tEnter your choice : echo Enter your choice : \c echo dont worry echo The date of today is date

770 00440 0490-VHBE

85

ALCATEL UNIVERSITY

SHELL SCRIPTS

On BSD based systems, you can save the cursor position with the -n option (e.g. echo -n Enter your choice : ). 10.16 More on quotes

10.16.1

Double quotes

All characters that have a special meaning to the shell (such as * ? > < >> | [ ] ( ) & # ; and whiteSpace) loose their special meaning when they appear between a pair of quotes or after \. e.g.
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

echo > will return a syntax error, and echo > will write a > on standard output. echo * will show the file names in the current directory, and echo * will write a * on standard output.

e.g.

Exceptions on this rule are $ and \. e.g. var=hello echo $var will write the word hello on standard output.

10.16.2

Single quotes

The rules for single quotes are the same as for double quotes except that the special meaning of $ and \ are removed too. e.g. var=hello echo $var will echo $var on standard output.

ALCATEL UNIVERSITY

86

770 00440 0490-VHBE

SHELL SCRIPTS

10.16.3

Using quotes within quotes

Good solutions are : echo The echo The echo The echo The Bad solutions are : echo The echo The 10.16.4

title title title title

of of of of

the the the the

book book book book

is is is is

C++ C++ \C++\ \C++\

title of the book is C++ title of the book is C++

Backward quotes

If the output of one command needs to be used as parameter to another command, the command can be included in backward quotes. e.g. echo The day of today is date
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

10.17

Set the options for the terminal to switch off echo: stty

Syntax : stty [option] The stty command can be used for setting the terminals options. The option we discuss here is the echo option . The command stty -echo makes that everything you enter on the keyboard will not be displayed on the screen until you enter the command stty echo Example : echo stty read stty Enter password : \c -echo password echo

770 00440 0490-VHBE

87

ALCATEL UNIVERSITY

THE KORN SHELL

11THE KORN SHELL


As noted earlier, the Korn shell is a relatively new shell developed by David Korn. He designed this shell to be upwards compatible with the Bourne shell, so that programs written for the Bourne shell also run under the Korn shell. The Korn shell provides you with almost all of the Bourne shells features, as well as many new ones. The main added features in the Korn shell are :
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

1. Command line editing : the ability to edit your command line using vi or emacs commands. 2. Command history : the ability to easily recall previously entered commands, make changes to them, and re-execute them. 3. Built-in integer arithmetic and string manipulation capabilities. 4. Aliasing : the ability to assign alternate names to commands and commands sequences. 5. Arrays. 6. Job control : the ability to automatically monitor and control programs executing in background.

In this chapter, we will discuss some of these features.

ALCATEL UNIVERSITY

88

770 00440 0490-VHBE

THE KORN SHELL

11.1 Running the Korn shell The Korn shell is stored in a file named ksh. When you start up the Korn shell, it looks for an exported variable called ENV. If it is set, the file specified by ENV will be executed. The file denoted by the ENV variable usually contains commands to set up the Korn shells environment. One thing you should start with is to have it set the SHELL variable to the Korn shell. In this way as long as you are in the Korn shell, new shells that get started will be the Korn shell. So, SHELL=/bin/ksh export SHELL ENV=.kshrc

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

The file .kshrc is executed each time ksh is invoked. Typical uses are for alias and function definitions, and for setting options with set. 11.2 Edit the command line using vi commands With the Korn shell, you can edit the command line before you hit the Return key. You can do this by entering vi commands or emacs commands. Here, we will just talk about the vi edit mode. First of all, you have to select an edit mode : set -o vi You can put this line into your ENV file to automatically start up the Korn shell with vi edit mode turned on. When you now write a mistake in the command line, you leave input mode by pressing Esc. Then you are in command mode and you can enter vi commands in order to correct the mistake. Basic vi line edit commands h l b w 0 $ x a i move one character to the left move one character to the right move one word to the left move one word to the right move to start of line move to end of line delete character at cursor enter text after the current character enter text before the current character

770 00440 0490-VHBE

89

ALCATEL UNIVERSITY

THE KORN SHELL

For a complete list of commands, see the description of the vi editor. After a command is executed, you are placed back in input mode. 11.3 History mechanism As noted before, the Korn shell keeps a history of recently entered commands. The history file is maintained across login sessions, and can be shared by several simultaneous instances of ksh. To access these commands, you can use emacs commands or vi commands. Here, we focus on vi : use k, j or / after pressing Esc, or you can use the r command. The k or - command replaces the current line on your terminal with the previously entered command. Every time k is used, the current line is replaced by the previous line of the history list. The j or + command is the inverse of the k command and is used to display the next command in the history list. The / command is used to search through the command history for a command containing a string. If the / is entered, followed by a string, then the Korn shell will search backward through its history to find the most recently executed command that contains that string anywhere on the command line. If the command that is displayed is not the one you are interested in, then you can continue the search through the command history by simply typing in / and pressing Return. When you have found the command in the history, you can edit it by using the vi commands we have already discussed. The r command re-executes immediately a previously entered command. It has different forms : Without argument, the command re-executes the last command of the history list. The argument is the beginning of a previously entered command. e.g. r cat will execute the last command in the history buffer which starts with cat. The argument contains a string to be replaced. e.g. r A=B will search for the last command entered containing an A and will replace the A by B and then the command will be executed.

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

ALCATEL UNIVERSITY

90

770 00440 0490-VHBE

THE KORN SHELL

11.4 Aliassing Aliasses can be used to redefine commands. They can be created with the alias command, and they can be removed with the unalias command. Example : alias ls=ls -l alias unalias ls defines the alias ls shows a list of all aliasses known removes ls from the alias list

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

770 00440 0490-VHBE

91

ALCATEL UNIVERSITY

THE emacs EDITOR

12THE emacs EDITOR FAMILY


12.1 Introduction Xemacs and GNU emacs are some of the most powerful editors existing today (february 1999). Xemacs is a version of GNU emacs made especially for the X window system by a different group of designers, but it has been kept in-sync with further versions of GNU emacs. In this chapter we explain how to use Xemacs with the mouse but we also explain the key combinations that can be used in both Xemacs and GNU emacs, or that are in some cases the only way to do something. The contents of this chapter has been determined according to the needs for the course UNIX for integration testers for department VE4. This chapter is based on Xemacs 20.4 as configured on the Alcatel Bell VE network on 19th of february 1999 (Xemacs and GNU emacs can be heavily customised: binding of key combinations to emacs functions, addition of new functions, customisation of menus,). The tables with keystrokes in this chapter are based on the default meaning of the key combinations. Those tables are put together in a special sub-chapter because while you are getting more familiar with emacs, you will want to quickly browse through those tables to find the command you need and the corresponding keystrokes. An editor from the emacs family is a complete working environment. You can start an emacs in the morning and work all day while not leaving it. You can use it to edit, rename, delete and copy files; to compile programs; to do interactive work with the UNIX shell; to read and organize electronic mail, and so on. Before window systems like X became popular, an emacs editor often served as a complete windowing system of its own. Xemacs and GNU emacs are also infinitely flexible; you can write your own commands, change the keys that are associated with commands and do just about anything you want. emacs isnt so much an editor as a family of editors. There are a lot of similarities; all of these editors allow you to mix text and editor commands freely; most support work in multiple windows; they all provide some kind of support to work with special file types like C or Lisp programs; most are heavily customisable, usually by programming in some dialect of Lisp. In this chapter, we focus on Xemacs (originally called Lucid emacs) and GNU emacs (from the Free Software Foundation) which are the most powerful and customisable members of the family. We cover only a basic set of features and commands, to get you started. Some examples are given of more advanced features such as customisation. The lower levels of GNU emacs are written in the C language. This comprises an interpreter for emacs Lisp (based on maclisp with some influence from the Common Lisp standard). This emacs Lisp interpreter can handle text or byte code-compiled emacs Lisp, which executes faster. The higher levels of emacs are written in emacs Lisp (e.g. the functions for the emacs commands).

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

ALCATEL UNIVERSITY

92

770 00440 0490-VHBE

THE emacs EDITOR

12.2 Keyboard-based command input Emacs keyboard commands consist of a modifier such as Ctrl (Control key), ESC (Escape key) or META (META key) followed by 1 or 2 characters. A META key is not present on all keyboards (there are 2 on Sun workstations: it are the keys marked with a diamond on either side of the space bar), so if you dont have a META key, use ESC instead (with the difference that you can hold down the META key but have to press and release the ESC key). Conventions used: Ctrl-g means: hold down the Ctrl key and type a g
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

META-g means: hold down the META key and type a g ESC g means: press and release ESC key and then type a g The most commonly used commands (such as cursor movement commands) are bound to Ctrl-n (where n is any character). Slightly less commonly used commands are bound to ESC n (where n is any character). Other commonly used commands are bound to Ctrl-x something (Ctrl-x followed by something else - one or more characters or another control sequence). Example: file manipulation commands. Some specialised commands are bound to Ctrl-c something. These commands often relate to one of the more specialised modes (Lisp, C, Pascal, mode). A mode describes the way emacs will handle text (automatic formatting depending on the programming language selected) or the way Xemacs will use colours depending on the programming language syntax (e.g. colours for keywords, strings, comments,) Finally, any command can be given by using the long command name which is in fact the name of the Lisp function corresponding to the command: ESC x long-command-name Enter or META-x long-command-name Enter

770 00440 0490-VHBE

93

ALCATEL UNIVERSITY

THE emacs EDITOR

12.3 Starting Xemacs on the VE desktop Click the left mouse button on the desktop: you get a pop-up menu where you can select Edit/Browse document and then Xemacs and then version20.4 12.4 Abort command in progress Ctrl-g allows you to abort any command (for instance while it is prompting for more input and you decide you dont want the command after all).

12.5 Ways to open an existing file Click with left button on the open file icon or select the item open from the file menu. A dialog box appears which corresponds to the working directory and which consists of 2 parts. In the left part subdirectories are shown, In the right part files. Using a 3-button mouse If the file you want is in the working directory, use the scroll bars of the right part until you see the wanted file and then put the mouse pointer on the file name and click the middle button: the file is immediately opened in an emacs buffer. If the file is in a subdirectory, first use the scroll bars of the left part until you see a wanted subdirectory and put the mouse pointer on the subdirectory name and click the middle button. The subdirectory is shown at the bottom and the left and right part now show subdirectories and files in the selected subdirectory. Continue this until you see the wanted file. Then put the mouse pointer on the file name and click the middle button to open the file. Using a two-button mouse and the keyboard If the file you want is in the working directory, use the scroll bars of the right part until you see the wanted file and then put the mouse pointer on the file name and click on it with the left button. Use the Enter key to open the file in an emacs buffer. If the file is in a subdirectory, first use the scroll bars of the left part until you see a wanted subdirectory and put the mouse pointer on the subdirectory name and click on it with the left button. Use the Enter key to get the list of subdirectories (left part) and files (right part) for the directory you selected.

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

ALCATEL UNIVERSITY

94

770 00440 0490-VHBE

THE emacs EDITOR

Continue this until you see the wanted file. Then put the mouse pointer on the file name and click with the left button. Use the Enter key to open the file in an emacs buffer. Using only the keyboard Type Ctrl-x Ctrl-f. In the message area at the bottom of the Xemacs/emacs frame you get ~/. This represents your working directory. You can then type directly a filename or (a) subdirectory name(s) and finally a filename. If you want to switch to dired (directory editor) view to see more details about the directories and files: When the wanted directory has been selected with one of the methods described earlier, remove the trailing / and use the Enter key. You get an emacs buffer in which the dired view of the directory is shown. You can see the details you normally get with the UNIX command ls -al. See the keystrokes table with key combinations for dired.

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

12.6 Start a new file Same as for opening an existing file, except of course that you have to supply the filename.

12.7 Buffers and Windows Concepts A Buffer is a data structure related to a file or the output produced by some program. Emacs does not edit an actual file. Rather, it puts the contents of the file into a temporary buffer and edits that. Like files, Emacs buffers have names. The name of a buffer is usually the same as the name of the corresponding file. There are, however, buffers that are not tied to a particular file, such as *scratch* (a scratch pad buffer) and *help* (the buffer used by the help facility). A Window is a part of the emacs area on the screen that can be used to display an emacs buffer. Several Windows can display parts of the same emacs buffer. In the next paragraphs we describe Buffer/Window handling in Xemacs with the mouse. See keystrokes table for keyboard-only handling of Buffers/Windows.

770 00440 0490-VHBE

95

ALCATEL UNIVERSITY

THE emacs EDITOR

Selecting Buffers in a Window With the mouse, click inside the Window, then select the buffers menu and select the wanted buffer. Adding a Window With the mouse, select the file menu and select Split Window Removing a Window With the mouse, click inside the Window you want to remove, select the file menu and select Un-split (Keep others). Deleting a Buffer
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

With the mouse, click inside the Window displaying the buffer, select the file menu and select Delete Buffer ..

12.8 Moving the cursor in a Buffer See keystrokes table for Cursor movement 12.9 Search for a string See keystroke tables for Incremental search commands and Non incremental search. In the edit menu you have also Search for an incremental search.

12.10

Getting Help on screen Xemacs offers the largest amount of help of all emacs family editors. For the more limited help of GNU emacs: see the keystrokes table for help. We here present the help information as it can be selected from the Xemacs menu Help or with Xemacs keystrokes. All the help information comes into an emacs buffer, so you can use the emacs search facilities to search for a string concerning what you are looking for. To read a tutorial about the use of emacs:

ALCATEL UNIVERSITY

96

770 00440 0490-VHBE

THE emacs EDITOR

Help Basics Tutorial (or Ctrl-h t) To read a local frequently asked questions list: Help Xemacs FAQ Faq (local) (or Ctrl-h F) To type a key combination and get into the part of the emacs manual describing its default use: Help Lookup in Info Key Binding (or Ctrl-h Ctrl-k) To get information about a command by typing its long command name: Help Lookup in Info Command (or Ctrl-h Ctrl-c) To get information about an emacs lisp function (not a command function) by typing the functions name: Help Lookup in Info Function
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

To get info about a certain topic in the manual: Help Lookup in Info Topic (or Ctrl-h Ctrl-i) In the buffer you will notice topic names in bold black: they are a kind of hyperlinks: you can click on them and press Enter to get detailed info. To get the info from the UNIX man pages (you cannot use an emacs shell buffer (a buffer linked to an instance of your UNIX shell) to look at the man pages via the standard UNIX man command: the output looks garbled): Help Manuals Unix Manual To try to get info when you dont know a functions, a commands or a macros name but you know what it is about: Help Commands & Keys Apropos To get details about the command currently bound to a key combination: Help Commands & Keys Key (or Ctrl-h k) To get a list of current key bindings to commands: Help Commands & Keys Bindings (or Ctrl-h b) To get a list of mouse events bindings to commands: Help Commands & Keys Mouse Bindings (or Ctrl-h Ctrl-p) To get the keystrokes to which a command is bound: Help Commands & Keys Locate Command (or Ctrl-h w)

770 00440 0490-VHBE

97

ALCATEL UNIVERSITY

THE emacs EDITOR

12.11

Basic editing in a buffer Selecting text: use the mouse left button to drag it over the area of text you want to select. Cut/Copy: select the appropriate item in the edit menu. Paste: position the mouse pointer and select paste from the edit menu. Saving your work: click on save icon (diskette) or Ctrl-x Ctrl-s.

12.12

Search/Query and Replace See keystrokes table for Search and replace and table Query - replace.

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

12.13

Print a buffer Use the print icon or select from menu file item print buffer. Using the keyboard: see keystrokes table printing commands

12.14

Search using Regular Expressions

A regular expression (regexp, for short) is a pattern that denotes a set of strings, possibly an infinite set. Searching for matches for a regexp is a powerful operation that editors on Unix systems have traditionally offered. In Xemacs, you can search for the next match for a regexp either incrementally or not. Incremental search for a regexp is done by typing Meta-Ctrl-s (isearch-forward-regexp). This command reads a search string incrementally just like Ctrl-s, but it treats the search string as a regexp rather than looking for an exact match against the text in the buffer. Each time you add text to the search string, you make the regexp longer, and the new regexp is searched for. A reverse regexp search command isearch-backward-regexp also exists, but no key runs it. All of the control characters that do special things within an ordinary incremental search have the same functionality in incremental regexp search. Typing Ctrl-s or Ctrl-r immediately after

ALCATEL UNIVERSITY

98

770 00440 0490-VHBE

THE emacs EDITOR

starting a search retrieves the last incremental search regexp used: incremental regexp and non-regexp searches have independent defaults. Non-incremental search for a regexp is done by the functions re-search-forward and research-backward. You can invoke them withMeta-x or bind them to keys. You can also call re-search-forward by way of incremental regexp search withMeta-Ctrl-s Enter. 12.14.1 Syntax of Regular Expressions

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

Regular expressions have a syntax in which a few characters are special constructs and the rest are ordinary. An ordinary character is a simple regular expression which matches that character and nothing else. A special character is $ | ^ | . | * | + | ? | [ | ] | \. No new special characters will be defined. Any other character appearing in a regular expression is ordinary, unless a \ precedes it. For example, f is not a special character, so it is ordinary, and therefore f is a regular expression that matches the string f and no other string. (It does not match the string ff.). Any two regular expressions A and B can be concatenated. The result is a regular expression which matches a string if A matches some amount of the beginning of that string and B matches the rest of the string. As a simple example, you can concatenate the regular expressions f and o to get the regular expression fo, which matches only the string fo. To do something nontrivial, you need to use one of the following special characters: 12.14.1.1 . (Period) special character is a special character that matches any single character except a newline. Using concatenation, you can make regular expressions like a.b, which matches any three-character string which begins with a and ends with b. 12.14.1.2 * special character is not a construct by itself; it is a suffix, which means the preceding regular expression is to be repeated as many times as possible. In fo*, the * applies to the o, so fo* matches one f followed by any number of os. The case of zero o is allowed: fo* does match f. * always applies to the smallest possible preceding expression. Thus, fo* has a repeating o, not a repeating fo.

770 00440 0490-VHBE

99

ALCATEL UNIVERSITY

THE emacs EDITOR

The matcher processes a * construct by immediately matching as many repetitions as it can find. Then it continues with the rest of the pattern. If that fails, backtracking occurs, discarding some of the matches of the *-modified construct in case that makes it possible to match the rest of the pattern. For example, matching ca*ar against the string caaar, the a* first tries to match all three as; but the rest of the pattern is ar and there is only r left to match, so this try fails. The next alternative is for a* to match only two as. With this choice, the rest of the regexp matches successfully. 12.14.1.3 + special character is a suffix character similar to * except that it requires that the preceding expression be matched at least once. For example, ca+r will match the strings car and caaaar but not the string cr, whereas ca*r would match all three strings.
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

12.14.1.4 ? special character is a suffix character similar to * except that it can match the preceding expression either once or not at all. For example, ca?r will match car or cr; nothing else. 12.14.1.5 [ ] special characters [ begins a character set, which is terminated by a ]. In the simplest case, the characters between the two form the set. Thus, [ad] matches either one a or one d, and [ad]* matches any string composed of just as and ds (including the empty string), from which it follows that c[ad]*r matches cr, car, cdr, caddaar, etc. You can include character ranges in a character set by writing two characters with a - between them. Thus, [a-z] matches any lower-case letter. Ranges may be intermixed freely with individual characters, as in [a-z$%.], which matches any lower-case letter or $, %, or period. Note that inside a character set the usual special characters are not special any more. A completely different set of special characters exists inside character sets: ], -, and ^. To include a ] in a character set, you must make it the first character. For example, []a] matches ] or a. To include a -, write ---, which is a range containing only -. To include ^, make it other than the first character in the set. [^anyExceptThese]

ALCATEL UNIVERSITY

100

770 00440 0490-VHBE

THE emacs EDITOR

[^ begins a complement character set, which matches any character except the ones specified. Thus, [^a-z0-9A-Z] matches all characters except letters and digits. ^ is not special in a character set unless it is the first character. The character following the ^ is treated as if it were first (- and ] are not special there). Note that a complement character set can match a newline, unless newline is mentioned as one of the characters not to match. 12.14.1.6 ^ special character is a special character that matches the empty string, but only if at the beginning of a line in the text being matched. Otherwise, it fails to match anything. Thus, ^foo matches a foo that occurs at the beginning of a line.
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

12.14.1.7 $ special character is similar to ^ but matches only at the end of a line. Thus, xx*$ matches a string of one x or more at the end of a line. 12.14.1.8 \ special character does two things: it quotes the special characters (including \), and it introduces additional special constructs. Because \ quotes special characters, \$ is a regular expression that matches only $, and \[ is a regular expression that matches only [, and so on. Note: for historical compatibility, special characters are treated as ordinary ones if they are in contexts where their special meanings make no sense. For example, *foo treats * as ordinary since there is no preceding expression on which the * can act. It is poor practice to depend on this behavior; better to quote the special character anyway, regardless of where it appears. Usually, \ followed by any character matches only that character. However, there are several exceptions: characters which, when preceded by \, are special constructs. Such characters are always ordinary when encountered on their own. Here is a table of \ constructs. \| specifies an alternative. Two regular expressions A and B with \| in between form an expression that matches anything A or B matches.

770 00440 0490-VHBE

101

ALCATEL UNIVERSITY

THE emacs EDITOR

Thus, foo\|bar matches either foo or bar but no other string. \| applies to the largest possible surrounding expressions. Only a surrounding \(regularexpression\) grouping can limit the grouping power of \|. Full backtracking capability exists to handle multiple uses of \|. \(regularExpression\) is a grouping construct that serves three purposes: 1. To enclose a set of \| alternatives for other operations. Thus, \(foo\|bar\)x matches either foox or barx. 2. To enclose a complicated expression for the postfix * to operate on. Thus, ba\(na\)* matches bananana, etc., with any (zero or more) number of na strings.
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

3. To mark a matched substring for future reference. This last application is not a consequence of the idea of a parenthetical grouping; it is a separate feature which happens to be assigned as a second meaning to the same \( \) construct because in practice there is no conflict between the two meanings. Here is an explanation: \digit after the end of a \( \) construct, the matcher remembers the beginning and end of the text matched by that construct. Then, later on in the regular expression, you can use \ followed by digit to mean match the same text matched the digitth time by the\( \) construct. The strings matching the first nine \( \) constructs appearing in a regular expression are assigned numbers 1 through 9 in order that the open-parentheses appear in the regular expression. \1 through \9 may be used to refer to the text matched by the corresponding \( \) construct. For example, \(.*\)\1 matches any newline-free string that is composed of two identical halves. The \(.*\) matches the first half, which may be anything, but the \1 that follows must match the same exact text. \ matches the empty string, provided it is at the beginning of the buffer. \ matches the empty string, provided it is at the end of the buffer.

ALCATEL UNIVERSITY

102

770 00440 0490-VHBE

THE emacs EDITOR

\b matches the empty string, provided it is at the beginning or end of a word. Thus, \bfoo\b matches any occurrence of foo as a separate word. \bballs?\b matches ball or balls as a separate word. \B matches the empty string, provided it is not at the beginning or end of a word. \< matches the empty string, provided it is at the beginning of a word. \> matches the empty string, provided it is at the end of a word. \w matches any word-constituent character. The editor syntax table determines which characters these are. \W matches any character that is not a word-constituent. \scode matches any character whose syntax is code. code is a character which represents a syntax code: thus, w for word constituent, - for whitespace, ( for open-parenthesis, etc. \Scode matches any character whose syntax is not code. 12.14.2 Regular expression example

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

Here is a complicated regexp used by Emacs to recognise the end of a sentence together with any whitespace that follows. It is given in Lisp syntax to enable you to distinguish the spaces from the tab characters. In Lisp syntax, the string constant begins and ends with a doublequote. \ stands for a double-quote as part of the regexp, \\ for a backslash as part of the regexp, \t for a tab and \n for a newline. [.?!][]\)]*\\($\\|\t\\| \\)[ \t\n]*

This regexp contains four parts: a character set matching period, ? or !; a character set matching close-brackets, quotes or parentheses, repeated any number of times; an alternative in backslash-parentheses that matches end-of-line, a tab or two spaces; and a character set matching whitespace characters, repeated any number of times.

770 00440 0490-VHBE

103

ALCATEL UNIVERSITY

THE emacs EDITOR

12.15

Macros Record a macro Start recording by using menu edit and item start macro recording Type your command as you would normally do. End the macro recording by using menu edit and item end macro recording. Name the last recorded macro ESC x name-last-kbd-macro Enter name Enter To use the named macro ESC x name Save macro permanently Find a file (e.g. .emacs, your personal customisation file in your home directory) and move to the end of the file to add there an emacs lisp function call to define the named macro: ESC x insert-kbd-macro Enter name Enter Save the file Load a file if it is not .emacs ESC x load-file Enter filepathandname Enter

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

12.16

Emacs modes

Emacs achieves its versatility by having various editing modes in which it behaves slightly differently. When writing, you want features like word wrap, so that you dont have to press Enter at the end of every line. When programming, the code must be formatted according to the language you are using. There are major modes (a buffer can only be in 1 major mode at a time, such as fundamental mode (no special behaviour) or Lisp mode, or C mode, ) and minor modes (one or more can be active at a time such as overwrite mode (overwrite characters instead of inserting them) and auto-save mode (regularly save the file to disk)). See the help info for more details.

ALCATEL UNIVERSITY

104

770 00440 0490-VHBE

THE emacs EDITOR

12.17

A UNIX shell in a buffer

You can open a buffer to a UNIX shell and use it to enter any UNIX command. See the keystrokes table about a UNIX shell. Note: the man command, when entered in a shell buffer, will give garbled output: use the Xemacs help instead to see the man pages.

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

770 00440 0490-VHBE

105

ALCATEL UNIVERSITY

THE emacs EDITOR

12.18

Emacs keystrokes tables (default key bindings)

The tables describe default keystrokes meaning for GNU emacs as well as Xemacs. From GNU Emacs version 19.30 on it is also possible to use a menu bar with menus. The small character text given for some keystrokes describes the menu selections for GNU emacs 19.30 or later. Help commands Keystrokes Ctrl-h Ctrl-h f
HelpDescribe Function

long command name help-command describe-funtion describe-key help-with-tutorial


info-goto-emacs-command-mode

Ctrl-h k
HelpDescribe key
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

Ctrl-h t
HelpEmacs Tutorial

Action Enter the online help system Gives online help for a given command name Gives online help for a given keystroke sequence Start the Emacs tutorial Start the info documentation reader

Ctrl-h I
HelpBrowse Manuals

ALCATEL UNIVERSITY

106

770 00440 0490-VHBE

THE emacs EDITOR

File handling commands and exit Emacs Keystrokes Ctrl-x Ctrl-f


FilesOpen File

long command name find-file find-alternate-file

Ctrl-x Ctrl-v

Ctrl-x I
FilesInsert File

insert-file save-buffer write-file save-buffers-kill-emacs

Ctrl-x Ctrl-s Ctrl-x Ctrl-w


FilesSave Buffer As

Ctrl-x Ctrl-c
FilesExit Emacs
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

Action Find file and read it in a new buffer Read an alternate file, replacing the one read with Ctrl-x Ctrl-f Insert file at cursor position Save file Write buffer contents to file Exit Emacs

Cursor movement You can move the cursor by character, word, line, sentence, paragraph, screen or page. Emacs defines a sentence pretty strictly. You need two spaces after the final punctuation mark, unless you are at the end of the line. To Emacs, paragraphs are either indented with a tab or at least one space or have blank lines between them (block style). A variable called page-delimiter defines what constitutes a page break. If there are no Emacsrecognized page breaks in the file, Emacs regards the whole buffer as one big page.

770 00440 0490-VHBE

107

ALCATEL UNIVERSITY

THE emacs EDITOR

Keystrokes Ctrl-f Ctrl-b Ctrl-p Ctrl-n ESC f ESC b Ctrl-a Ctrl-e ESC e ESC a
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

long command name forward-char backward-char previous-line next-line forward-word backward-word beginning-of-line end-of-line forward-sentence backward-sentence forward-paragraph backward-paragraph scroll-up scroll-down forward-page backward-page beginning-of-buffer end-of-buffer goto-line goto-char

ESC } ESC { Ctrl-v ESC v Ctrl-x ] Ctrl-x [ ESC < ESC > (no keystrokes) (no keystrokes)

Action Move forward one character (right) Move backward one character (left) Move to previous line (up) Move to next line (down) Move one word forward Move one word backward Move to beginning of line Move to end of line Move forward one sentence Move backward one sentence Move forward one paragraph Move backward one paragraph Move forward one screen Move backward one screen Move forward one page Move backward one page Move to begin of file Move to end of file Go to line n of file Go to char n of file

(no keystrokes) no default keystrokes (use ESC x long command name Enter) Keystrokes Ctrl-l ESC n Ctrl-u n long command name recenter digit-argument universal-argument Action Redraw screen with current line in the center Repeat the next command n times Repeat the next command n times (4 if you omit n)

ALCATEL UNIVERSITY

108

770 00440 0490-VHBE

THE emacs EDITOR

Region A region is a part of a file buffer that can be acted upon. When a region has been marked, it can be deleted, copied, ... Commands to mark a region Keystrokes Ctrl-@ Ctrl-x Ctrl-x ESC h Ctrl-x Ctrl-p Ctrl-x h
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

long command name set-mark-command exchange-point-and-mark mark-paragraph mark-page mark-whole-buffer

Action Mark the begin of a region Exchange location of cursor and mark Mark paragraph as a region Mark page as a region Mark buffer as a region

Commands for deletion, copy and paste Keystrokes Ctrl-d DEL ESC d ESC DEL Ctrl-k ESC k Ctrl-x DEL Ctrl-y or SHIFT-INS
EditPaste Most recent

long command name delete-char delete-backward-char kill-word backward-kill-word kill-line kill-sentence backward-kill-sentence yank kill-region kill-paragraph backward-kill-paragraph kill-ring-save

Ctrl-w or SHIFT-DEL
EditCut

Action Delete character under cursor Delete previous character Delete next word Delete previous word Delete from cursor to end of line Delete next sentence Delete previous sentence Restore what you have deleted Delete a marked region Delete next paragraph Delete previous paragraph Copy the region (so it can be pasted) Undo

(no keystrokes) (no keystrokes) ESC w


EditCopy

Ctrl-x u

770 00440 0490-VHBE

109

ALCATEL UNIVERSITY

THE emacs EDITOR

Incremental search commands Incremental search starts to work from the moment you type the first character of the search string. For example, if you are searching the word meter, Emacs finds the next m as soon as you type the m; it finds the next me as soon as you type the e, and so on. Keystrokes Ctrl-s long command name isearch-forward Action Start incremental search forward by search string. Also, find next occurrence (forward) of search string Start incremental search backward; follow by search string. Also, find next occurrence (backward) of search string Exit a search Cancel incremental search Delete character from search string Start an incremental search with the word the cursor is on as the search string Start an incremental search with the text from the cursor position to the end of the line as the search string Start an incremental search with what was recently killed as the search string Repeat previous search

Ctrl-r

isearch-backward

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

Enter Ctrl-g DEL Ctrl-s Ctrl-w

(none) keyboard-quit (none) (none)

Ctrl-s Ctrl-y

(none)

Ctrl-s ESC y

(none)

Ctrl-s Ctrl-s (none) Non incremental search Keystrokes Ctrl-s Enter searchstring Enter Ctrl-s Ctrl-r Enter searchstring Enter Ctrl-r x

Action Start nonincremental search forward Repeat search forward Start nonincremental search backwards Repeat search backward

ALCATEL UNIVERSITY

110

770 00440 0490-VHBE

THE emacs EDITOR

Search and replace When you want to replace every instance of a given string, you can use the replace-string command: ESC x replace-string Enter searchstring Enter replacementstring Enter Query - replace Keystrokes ESC %
SearchQuery Replace

Action Start query-replace Replace searchstring with newstring and go to the next instance of searchstring Dont replace; move to next instance Replace the current instance and quit Replace and let me see the result before moving on (Press SPACE or y to move on) Replace all the rest and dont ask Back up to the previous instance Exit query-replace Delete this instance and enter a recursive edit (so you can make a custom replacement) Exit recursive edit and resume query-replace Exit recursive edit and exit query-replace

SPACE or y DEL or n . , ! ^ Enter or q Ctrl-w ESC Ctrl-c Ctrl-]

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

770 00440 0490-VHBE

111

ALCATEL UNIVERSITY

THE emacs EDITOR

Regular expression search commands Keystrokes ESC Ctrl-s Enter


SearchRegexp Search

long command name re-search-forward re-search-backward isearch-forward-regexp

ESC Ctrl-r Enter


SearchRegexp Search Backwards

Action Search for a regular expression forward Search for a regular expression backward Search incrementally forward for a regular expression Search incrementally backward for a regular expression Query-replace a regular expression Globally replace a regular expression unconditionally (use with caution)

ESC Ctrl-s

ESC Ctrl-r

isearch-backward-regexp

(no keystrokes)
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

query-replace-regexp replace-regexp

SearchQuery Replace Regexp

(no keystrokes)

ALCATEL UNIVERSITY

112

770 00440 0490-VHBE

THE emacs EDITOR

Buffer manipulation commands Keystrokes Ctrl-x b Ctrl-x Ctrl-b


BuffersList All Buffers

long command name switch-to-buffer list-buffers kill-buffer kill-some-buffers rename-buffer save-some-buffers

Action Move to the specified buffer Display the buffer list Delete the specified buffer Ask about deleting each buffer Change the buffers name to the specified name Ask whether you want to save each modified buffer

Ctrl-x k
FilesKill Current Buffer

(no keystrokes) (no keystrokes) Ctrl-x s

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

Buffer list commands Keystrokes Ctrl-n SPACE Ctrl-p D K S U X DEL ~ % 1 2 F O M V Q Action Move to the next buffer in the list (down one line) Move to the next buffer in the list Move to the previous buffer in the list (up one line) Mark buffer for deletion Mark buffer for deletion Save buffer Unmark buffer Execute other one-letter commands on the marked buffers Unmark the previous buffer in the list Mark buffer as unmodified Toggle read-only status of buffer Display buffer in a full screen Display this buffer and the next one in horizontal windows Replace buffer list with this buffer Replace other window with this buffer Mark buffers to be displayed in windows Display buffers marked with m Quit buffer list Occurs Immediately Immediately Immediately Press x Press x Press x Immediately Immediately Immediately Immediately Immediately Immediately Immediately Immediately Immediately Press v Immediately Immediately

770 00440 0490-VHBE

113

ALCATEL UNIVERSITY

THE emacs EDITOR

Handling of windows Keystrokes Long command name Ctrl-x ^ enlarge-window Ctrl-x 2 split-window-vertically Ctrl-x 3 split-window-horizontally Ctrl-x 1 delete-other-windows Ctrl-x 0 delete-window Ctrl-x o other-window Shell mode commands Keystrokes long command name (none) shell Ctrl-c Ctrl-c comint-interrupt-subjob
SignalsBREAK

Action Make window larger Split into 2 hor. windows Split into 2 vert. windows Back to 1 window Delete window Move to another window Action Enter shell mode Interrupt current job; equivalent to Ctrl-c in UNIX shells Send EOF character if at end of buffer; delete a character elsewhere Send EOF character Erase current line; equivalent to Ctrl-u in UNIX shells For non-X users, suspend or stop a job; Ctrl-z in UNIX shells Retrieve previous commands Retrieve subsequent commands Send input which is on current line Complete current command, filename or variable name Delete output from last command Move first line of output to top of window Move last line of output to bottom of window Move to previous command

Ctrl-d
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

comint-delchar-or-maybe-eof

Ctrl-c Ctrl-d
SignalsEOF

comint-send-eof comint-kill-input

Ctrl-c Ctrl-u

Ctrl-c Ctrl-z
SignalsSTOP

comint-stop-subjob

ESC p
In/OutPrevious Input

comint-previous-input comint-next-input comint-send-input comint-dynamic-complete

ESC n
In/OutNext Input

Enter TAB
CompleteComplete Before Point

Ctrl-c Ctrl-o
In/OutKill Current Output Group

comint-kill-output comint-show-output comint-show-maximum-output comint-previous-prompt

Ctrl-c Ctrl-r Ctrl-c Ctrl-e


In/OutShow Maximum Output

Ctrl-c Ctrl-p
In/OutBackward Output Group

ALCATEL UNIVERSITY

114

770 00440 0490-VHBE

THE emacs EDITOR

Ctrl-c Ctrl-n
In/OutForward Output Group

comint-next-prompt

Move to next command

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

770 00440 0490-VHBE

115

ALCATEL UNIVERSITY

THE emacs EDITOR

Dired (Directory editor) commands Keystrokes Ctrl-x d


FilesOpen Directory

long command name dired dired-do-copy dired-flag-file-deletion dired-do-delete dired-find-file revert-buffer dired-do-chgrp dired-do-kill-lines dired-mark dired-next-line
dired-find-file-other-window

Action Start dired Copy file Flag for deletion Query for immediate deletion Edit file Reread the directory from disk Change group permissions Remove line from display (dont delete file) Mark with * Move to next line Find file in another window; move there Find file in another window; dont move there Print file Quit dired Query replace string in marked files Rename file Remove mark View file Delete files flagged with d Compress or uncompress file Remove all marks from all files

C
OperateCopy to

D
MarkFlag

D
OperateDelete

E
ImmediateFind This File

G
FilesRevert Buffer

G
OperateChange Group

K
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

M
MarkMark

N O
ImmediateFind in Other Window

Ctrl-o
ImmediateDisplay in Other Window

dired-display-file dired-do-print dired-quit dired-do-query-replace dired-do-rename dired-unmark dired-view-file dired-do-flagged-delete dired-do-compress dired-unmark-all-files

P
OperatePrint

Q Q R
OperateRename to

U
MarkUnmark

V
ImmediateView This File

X Z
OperateCompress

ESC DEL
MarkUnmark All

Dired (Directory editor) commands (continued) Keystrokes long command name Action

ALCATEL UNIVERSITY

116

770 00440 0490-VHBE

THE emacs EDITOR

~
MarkFlag Backup Files

dired-flag-backup-files

*
MarkMark Executables

dired-mark-executables dired-flag-auto-save-files

#
MarkFlag Auto-save Files

.
MarkMark Old Backups

dired-clean-directory dired-mark-directories dired-diff

/
MarkMark Directories

=
ImmediateDiff

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

ESC =
ImmediateCompare With Backup

dired-backup-diff dired-do-shell-command dired-next-marked-file dired-prev-marked-file dired-flag-files-regexp dired-mark-files-regexp dired-create-directory dired-next-dirline dired-prev-dirline dired-sort-toggle-or-edit

Flag backup files for deletion; Ctrl-u ~ removes flags Mark executables with *; Ctrl-u * unmarks Flag auto-save files for deletion; Ctrl-u # removes flags Flag numbered backups for deletion (if any) Mark directories with *; Ctrl-u / unmarks Compare this file to another file (the one at the mark) Compare this file with its backup file Ask for shell command to execute on the selected file Move to the next file marked with * or D Move to previous file marked with * or D Flag for deletion files that match regular expression Mark files that match regular expression Create a directory Move to next directory Move to previous directory Re-sort the Dired display by date or by filename (toggles between these)

!
OperateShell command

ESC }
MarkNext Marked

ESC {
MarkPrevious Marked

%d
RegexpFlag

%m
RegexpMark

+
ImmediateCreate Directory

>
SubdirNext Dirline

<
SubdirPrev Dirline

770 00440 0490-VHBE

117

ALCATEL UNIVERSITY

THE emacs EDITOR

Printing commands Keystrokes (long command) ESC x print-buffer Enter


ToolsPrint Buffer

Action Print the buffer (similar to UNIX pr | lpr) Print the region (similar to UNIX pr | lpr) Print buffer with no page numbers (similar to UNIX lpr) Print region with no page numbers (similar to UNIX lpr) From Dired, put the default print command into the minibuffer; you can change it or press Enter to execute it Print the buffer with text attributes

ESC x print-region Enter


ToolsPrint Region

ESC x lpr-buffer Enter ESC x lpr-region Enter ESC x dired-do-print Enter


OperatePrint

ESC x ps-print-buffer-with-faces Enter


ToolsPostscript Print Buffer

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

ALCATEL UNIVERSITY

118

770 00440 0490-VHBE

THE emacs EDITOR

12.19 A few examples of customising Xemacs/GNU emacs using emacs lisp As a first example, we bind a key combination to a macro: We assume you defined a macro, named it MyCuteMacro and had emacs store the macro as a call to the emacs lisp function defalias in a file you opened for that purpose (your .emacs file (loaded automatically) or some other file (to be loaded manually)). You should look for a key combination that is not used yet or else you will loose the old meaning of the key combination (without warning). Check the help menu, item lookup in Info. To bind the key combination Ctrl-x Ctrl-space to this macro, we have to call the emacs lisp function global-set-key as follows:
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

(global-set-key [(control x) (control space)] MyCuteMacro) Explanation: Everything in Lisp looks like a list, also a function call. Here we call the function global-setkey with as arguments the vector (a kind of array in emacs lisp) [(control x) (control space)] and MyCuteMacro. The vector contains 2 elements (control x) and (control space). They are both lists with as elements the symbols control and x, respectively control and space. The symbol control is a modifier, meaning one has to hold down the Ctrl key while typing x or space. The quote before MyCuteMacro is needed, because otherwise the Lisp system would try to find a variable called MyCuteMacro bound to a value. With the quote, MyCuteMacro will be considered as the name of the function to call when the key combination is used. You can add this call to global-set-key to the file containing the defalias call for the macro.

As a second example, we add a menu: We want to add a menu Special with an item hello that puts the message Hello! in the message area at the bottom of the Xemacs frame. To achieve this, we have to call the emacs lisp function add-menu as follows: (add-menu nil Special ([hello (message Hello!) t]))

770 00440 0490-VHBE

119

ALCATEL UNIVERSITY

THE emacs EDITOR

Explanation: The first argument, nil, indicates that the menu Special should be added on the menu bar of the Xemacs frame (otherwise, we have to specify the path that leads to the spot where the menu should be added, e.g. File as a path will result in the menu to be added as an item to the File menu from the menu bar). The second argument is the name of the menu (a string). The third argument is a list of menu items. Each menu item is a vector with 3 elements: the name of the item (a string), a lisp form to be evaluated when the item is selected (in this case a call to the message function) and an indication if the item is active (t for true in this case).

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

ALCATEL UNIVERSITY

120

770 00440 0490-VHBE

THE emacs EDITOR

12.20

References for more detailed information

About editing with Xemacs/GNU emacs:

GNU emacs: A good book about GNU emacs is: Learning GNU emacs, 2nd edition (1996) Debra Cameron, Bill Rosenblatt & Eric Raymond O Reilly ISBN 1-56592-152-6 The GNU emacs reference manual can be found at: http://www.delorie.com/gnu/docs/emacs/emacs_toc.html
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

Xemacs: The URL of the official site for Xemacs is: http://www.xemacs.org The Xemacs reference manual can be found at: http://www.cs.indiana.edu/elisp/xemacs/xemacs_toc.html

About programming in emacs lisp: A good book (in Dutch) for an introduction to Lisp is: Programmeren in Lisp, 2nd edition, 1986 Luc Steels Academic Service ISBN 90 6233 229 3 An introduction to programming in emacs lisp can be found at:
http://www.delorie.com/gnu/docs/emacs-lisp-intro/emacs-lisp-intro_toc.html

It is also available as a book: Programming in emacs lisp: an introduction ISBN 1-88211-441-8 The GNU emacs lisp reference manual can be found at: http://www.delorie.com/gnu/docs/elisp-manual-20/elisp_toc.html

770 00440 0490-VHBE

121

ALCATEL UNIVERSITY

THE emacs EDITOR

NT Emacs: Information about NT Emacs (equivalent of Xemacs for Windows NT/95/98) can be found at: http://www.cs.washington.edu/homes/voelker/ntemacs.html

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

ALCATEL UNIVERSITY

122

770 00440 0490-VHBE

SOME COMMANDS RELATED TO NETWORKING

13SOME COMMANDS RELATED TO NETWORKING


13.1 Command ypcat ypcat is a command related to the NIS (Network Information Service) of Sun, formerly known as the Yellow Pages (hence the yp in ypcat). ypcat enables you to display information from a NIS database. One example is the network-wide password file. The command: ypcat passwd Displays the contents of the network-wide password file. The NIS network information service uses a distributed, replicated database of dbm files (in ASCII form) contained in the /var/yp directory hierarchy on each NIS server.
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

A dbm database served by the NIS server is called a NIS map. A NIS domain is a subdirectory of /var/yp containing a set of NIS maps on each NIS server. A few maps available at BEC (Bell Education Centre): passwd The network-wide password file hosts The hostnames and their IP addresses services The TCP/IP network services present with their port number and the protocol used (e.g. UDP or TCP).

ypcat [ -{k|x} ] [ -d ypdomain ] mname Options: -k

Display the keys for those maps in which the values are null or the key is not part of the value. None of the maps derived from files that have an ASCII version in /etc fall into this class.

-d ypdomain Specify a domain other than the default domain. -x mname Display map nicknames. The NIS map name

ALCATEL UNIVERSITY

124

770 00440 0490-VHBE

SOME COMMANDS RELATED TO NETWORKING

13.2 Command rlogin The command rlogin enables you to log in on a remote computer running UNIX via a network. You must have an account on both computers unless there is a network-wide password file. If the file /etc/hosts.equiv on the remote computer specifies the name of your local computer, the remote computer will not prompt you to enter your password. Computers listed in the /etc/hosts.equiv are considered equally secure. An alternative way to specify a trusted relationship is on a per-user basis. Each users home directory can contain a file .rhosts that contains a list of trusted remote systems and users that dont have to type the password when they try to remotely login with the user id corresponding to that home directory. rlogin [-l userid ] hostname userid is needed when you want to remotely log in using a user id different from the one you are currently using for your local session. hostname is the name of the remote computer.
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

An advantage of the rlogin protocol is that it initiates your session using some information from your local session. Your terminal type (the value of the TERM shell variable) is propagated. Other information, such as baud rate and your screen (window) size, may also be propagated, depending on what the local and remote hosts support. The remote password file (if there is no network-wide password file) contains your user account information, such as the login shell and the login directory. All shell startup files (found on the remote) execute, which further initialises your environment. A disadvantage of rlogin is that it is a UNIX command, not available on other platforms. When you want to remotely login on a UNIX machine from a PC or whatever, you need the telnet protocol service. After the remote session has been started, you can do anything as if you were working on that remote computer locally.

13.3 Command telnet This command uses the telnet service (TCP/IP port nr 23). The telnet service is available not only on UNIX machines but also on PCs, so you can use the telnet service to work with a remote UNIX machine from a PC.

770 00440 0490-VHBE

125

ALCATEL UNIVERSITY

SOME COMMANDS RELATED TO NETWORKING

The remote telnet server initiates a log in just as you would get locally on that machine. After your log in user id and password are entered and verified, the session is initialised in the usual way using information from the password file on the server or the network-wide password file and executing the shell startup files. During the session you can do anything as if you would be working locally on the remote machine. telnet [-{8|E|l|c|d}] [-e escapeChar] [-l userid] [-n tracefile] [hostname [port]] If telnet is invoked without arguments, it enters command mode, indicated by its prompt: telnet> In this mode, it accepts and executes its associated commands. If it is invoked with arguments, it performs an open command with those arguments.
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

Some of the options for the telnet command: -8 Specifies an 8-bit data path. Negotiating the TELNET BINARY option is attempted for both input and output. Stops any character from being recognised as an escape character. Specifies an 8-bit data path on output. This causes the BINARY option to be negotiated on output. Disables the reading of the userstelnetrc file. Sets the initial value of the debug toggle to true.

-E -L

-c -d

-e escapeChar Sets the initial escape character (character to enter command mode) to escapeChar. escapeChar may also be a two character sequence consisting of ^ followed by one character. If the second character is ?, theDEL character is selected. Otherwise the second character is converted to a control character and used as the escape character. If the escape character is the null string, (i.e. -e ), it is disabled. -l userid When connecting to a remote system that understands the ENVIRON option, then userid will be sent to the remote system as the value for the variable USER. -n tracefile Opens tracefile for recording trace information.

ALCATEL UNIVERSITY

126

770 00440 0490-VHBE

SOME COMMANDS RELATED TO NETWORKING

Telnet service commands: Can be typed at the telnet> prompt. The escape character has to be used to get out of session input/output and enter command mode (telnet> prompt). To leave command mode, press Enter at the telnet> prompt. The most important commands are: open close mode Opens a Telnet session and leaves command mode. Close a Telnet session and exit Telnet. Sets one of the Telnet modes: Character most text typed is immediately sent to the remote host for processing. Line In line mode, character processing is done on the local system, under the control of the remote system (e.g. the remote switches off echo when a password has to be entered). Old line by line In old line by line mode, all text is echoed locally, and (normally) only completed lines are sent to the remote host. The local echo character (initially ^E) may be used to turn off and on the local echo. (Use this mostly to enter passwords without the password being echoed.). Displays the status (also the current Telnet mode)

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

status

For more commands and more details: see the man pages 13.4 Command ftp The command ftp gives access to the Internet file transfer protocol service. ftp [ -{d|i|n|v} ] [ hostname ] The ftp command is the user interface to the Internet standard File Transfer Protocol (FTP). ftp transfers files to and from a remote network site. The server host with which ftp is to communicate may be specified on the command line. If this is done, ftp immediately attempts to establish a connection to an FTP server on that

770 00440 0490-VHBE

127

ALCATEL UNIVERSITY

SOME COMMANDS RELATED TO NETWORKING

host; otherwise, ftp enters its command interpreter and awaits instructions from the user. When ftp is awaiting commands from the user, it displays the prompt ftp>. The following options may be specified at the command line, or to the command interpreter: -d -i -n Enable debugging. Turn off interactive prompting during multiple file transfers. Do not attempt auto-login upon initial connection. If auto-login is not disabled, ftp checks the .netrc file in the users home directory for an entry describing an account on the remote machine. If no entry exists, ftp will prompt for the login name of the account on the remote machine (the default is the login name on the local machine), and, if necessary, prompts for a password and an account with which to login. Show all responses from the remote server, as well as report on data transfer statistics. This is turned on by default if ftp is running interactively with its input coming from the users terminal.

-v
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

Some of the commands that can be specified to the command interpreter of ftp (at the ftp> prompt): open host [ port ] Establish a connection to the specified host FTP server. An optional port number may be supplied, in which case, ftp will attempt to contact an FTP server at that port. If the auto-login option is on (default setting), ftp will also attempt to automatically log the user in to the FTP server. account [ passwd ] Supply a supplemental password required by a remote system for access to resources once a login has been successfully completed. If no argument is included, the user will be prompted for an account password in a non-echoing input mode. dir [ remote-directory ] [ local-file ] Print a listing of the directory contents in the directory remote-directory, and, optionally, place the output in local-file. If no directory is specified, the current working directory on the remote machine is used. If no local file is specified, or localfile is -, output is sent to the terminal. cd remote-directory Change the working directory on the remote machine to remote-directory. cdup

ALCATEL UNIVERSITY

128

770 00440 0490-VHBE

SOME COMMANDS RELATED TO NETWORKING

Change the remote machine working directory to the parent of the current remote machine working directory. get remote-file [ local-file ] Retrieve the remote-file and store it on the local machine. If the local file name is not specified, it is given the same name it has on the remote machine. put local-file [ remote-file ] Store a local file on the remote machine. If remote-file is left unspecified, the local file name is used. delete remote-file Delete the file remote-file on the remote machine. bye Terminate the FTP session with the remote server and exit ftp. An EOF (End Of File) will also terminate the session and exit.

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

770 00440 0490-VHBE

129

ALCATEL UNIVERSITY

SOME COMMANDS RELATED TO XWINDOWS

14SOME COMMANDS RELATED TO XWINDOWS


14.1 Why a Graphical User Interface (GUI) ? The ability of UNIX to run several jobs at the same time (multitasking) is one of the reasons it is popular. As you become familiar with UNIX, you may find that working with one terminal screen can be awkward: Suppose you are editing a report and need to read your electronic mail periodically for information you want to add to the report. You can only run one job in the foreground--mail or the editor. These programs are both interactive, so it does not make sense to run one in the background. You need to alternate between the two programs: While working on the report do start the editor; edit for a while; write the results to a file; quit the editor; start up mail; read your mail; quit mail; done As long as you are alternating between jobs on a single terminal, you can see only one thing at a time--the contents of your mailbox or the report. If you could work at two terminals, side by side, you could read your mail on one and edit the report on the other. Soon, however, you might wish you head a third terminal--suppose the mail message referred you to an online database for more information? A Graphical User Interface (GUI) solves this problem by allowing you to create multiple windows on one terminal screen. Each window is a box that encloses a separate area on the screen. You can run a different utility in each window: special-purpose tools, such as a clock or calculator program or a shell so you can run familiar UNIX commands. As before, you can interact with only one program (window) at a time; but now you can create three windows on one terminal screen and see your report, your email, and the database at the same time. In fact something like that, though not a graphical interface, was already possible in early versions of the Emacs editor.

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

ALCATEL UNIVERSITY

130

770 00440 0490-VHBE

SOME COMMANDS RELATED TO XWINDOWS

14.2 What is a GUI? A user interface is that what enables the user to interact with, in this case, a computer system. The typical good old UNIX system user interface is the command line interface. In response to a shell prompt, You type a command line ending with a stroke at the return key. For example, to remove a file named junkfile you would type: $ rm junkfile One of the most common complaints about UNIX is that the command names and the command line interface are difficult to learn and use. To use a command, you must know its exact name; most are abbreviated and non-intuitive. Contrast that with the graphical user interface, which is designed so that you can manipulate pictures of objects on your screen. To get rid of an unwanted file via a GUI, you highlight the picture of the file and drag it across the screen until it collides with a picture of a trash can. This approach is so straightforward that many people can begin to use a GUI immediately, without being trained or reading elaborate instructions. Once you are familiar with the UNIX command line interface, however, a purely graphical interface can be tedious to use. Suppose you want to remove several files, named junkfile1, junkfile2 and junkfile3. Selecting the 3 files and then dragging them into the trash can is time-consuming, compared with the powerful shorthand of the command line interface: $ rm junkfile? So the ideal Graphical User Interface offers the best of both worlds, letting you chose between the full graphical approach and a shell running inside a window. 14.3 Command xterm This command starts a new command line interface window. In that window you get a shell prompt and can input any UNIX command. The output will appear in the same window. xterm [-sb] [-bg color] [-fg color] [sizeAndOrPosition] [title] & Notes: The order of the options is not significant. Because of the & the xterm command is executed in the background, so the prompt in your old window stays available. Where:

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

770 00440 0490-VHBE

131

ALCATEL UNIVERSITY

SOME COMMANDS RELATED TO XWINDOWS

-sb no scroll bars -bg background color: color is an identifier like blue, yellow, -fg foreground color (text color) sizeAndOrPosition -geometry [size][position] size nrOfCharactersxnrOfLines example: 100x24 position +nrOfPixelsFromLeftEdge+nrOfPixelsFromTopEdge -nrOfPixelsFromRightEdge-nrOfPixelsFromBottomEdge example: +30+10 title -title titleText 14.4 Command xkill xkill is the X windows equivalent of the command line command kill. It permits to point with the mouse to a window and when clicked, the process corresponding to the window will be killed. 14.5 Running an X application on a remote machine but displaying the window(s) on the local workstation xhost remoteMachineName rlogin remoteMachineName export DISPLAY=yourLocalMachineName:0.0 Start the X windows application from the command line The window(s) appear on your local display Work with the application Quit the application exit

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

ALCATEL UNIVERSITY

132

770 00440 0490-VHBE

SOME COMMANDS RELATED TO XWINDOWS

The xhost command is needed to tell the local system that it must accept input from the remote machine and as far as output is concerned, send the window events of the remote application window(s) on the local machine to the remote machine.

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

770 00440 0490-VHBE

133

ALCATEL UNIVERSITY

THE CRiSP EDITOR

15THE CRiSP EDITOR


CRiSP is an editor available for UNIX (X-Windows) as well as Windows 95/98/NT platforms with, of course, a graphical user interface. It is now (September 1999) the standard editor for System 12 software development using UNIX. Due to its graphical user interface, this editor is rather easy to use for the basic tasks, so we dont document here all these basic tasks and you will learn them by doing the exercises presented in this chapter. There is also extensive on-line help. A few of the most interesting features of CriSP apart from the basic editing tasks: CRiSP is customisable: you can change the binding of keys to commands and write macros which you can then bind to a key. Formatting of text and colouring of language elements according to a certain programming language known by CRiSP is possible: it is linked to the extension in the file name. CRiSP provides language colouring for the major languages in use nowadays, including CHILL. Not only colouring according to a certain language is possible, but CriSP also recognises procedures / functions and can show only the list of all procedures, each preceded by a small icon. By clicking on the icon, you can make CriSP show the text of the procedure. By clicking again on the icon, the procedure text is hidden again. 15.1 Start CRiSP From the CDE desktop for System 12 UNIX applications select AlcatelEdit/Browse documentsCrisp, or via the upward arrow icon above the Interleaf icon. 15.2 Use the HELP system The HELP of CRiSP works like the HELP of a Microsoft Windows-based program. Check it out by trying to find help about how to search for strings in a text. 15.3 Look at a CHILL listing and search in it 1. Copy the file /home/users/langedow/grin/chill.lst into your directory. 2. Open that copy in CRiSP.

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

ALCATEL UNIVERSITY

134

770 00440 0490-VHBE

THE CRiSP EDITOR

Fileopen There is no colouring of the CHILL text. 3. Make CRiSP recognise the .lst as an extension of a file whose text must be coloured according to CHILL Optionslanguage editing modes: tab language: choose CHILL for the colorizer 4. Make CRiSP show the list of procedures. In the Outline toolbar (leftmost vertical toolbar) click on icon for Show function definitions. If the Outline toolbar is not shown, add it via ViewToolbar. 5. Make CRiSP show the text of procedure Q_S300_MAIN_STATE Click on the icon in front of the line of procedure Q_S300_MAIN_STATE in the list. 6. Make CRiSP collapse the procedure again
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

Click again on the icon of the procedure 7. Make CRiSP show the whole file text again In Outline toolbar click on icon for Expand all hidden blocks 8. Search for occurrences of the string T_MSG_BUF_PTR FindSearch for (a normal search) or FindIntelligent search (an incremental search) 9. Access the file in 2 horizontal or vertical sub-windows Put your mouse cursor on a vertical or horizontal edge of the window at the spot where you want to split the current window and double-click. 10. Remove the sub-windows again Type F4 and use the arrow keys to move the caret (cursor indicating where you are in the text with your keyboard controls, not to be confused with the mouse cursor) into the sub-window border you want to remove.

770 00440 0490-VHBE

135

ALCATEL UNIVERSITY

THE CRiSP EDITOR

15.4 Edit a CHILL text 1. Start a new file, save it as abbreviated.CHILL and type the following text:
TEST_1 : MODULE SYNMODE PHONEMODE=ARRAY(1:10) RANGE (0:9); NEWMODE ABBR_DIR=ARRAY(1:5) STRUCT (ABBR RANGE (1:9), FULL ARRAY (1:10) RANGE(0:9)); NEWMODE SUBSCRIBER=STRUCT (NUMBER ARRAY (1:10) RANGE (0:9), AB_DIRECTORY ABBR_DIR); LOOK_UP : PROC (INDIVID ABBR_DIR LOC, DIALED RANGE (1:9), CALL_NO PHONEMODE LOC) RETURNS (BOOL); DCL FOUND BOOL, INDEX RANGE (1:5);
2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

FOUND := FALSE; DO FOR INDEX := 1 TO 5 WHILE NOT FOUND; IF INDIVID(INDEX).ABBR = DIALED THEN FOUND := TRUE; CALL_NO := INDIVID(INDEX).FULL; FI; OD; RETURN FOUND; END LOOK_UP; DCL BOOK ARRAY(1:2000) SUBSCRIBER; MAIN_1 : PROC(); DCL I INT, PHONE_NUM PHONEMODE; I := 10; IF LOOK_UP (BOOK(I).AB_DIRECTORY, 7, PHONE_NUM) THEN /* ... */ FI; END MAIN_1; END TEST_1;

2. Try cut-and-paste with the mouse by moving a procedure definition to another place. 3. Search and replace everywhere in the text the name BOOK by BOEK.

ALCATEL UNIVERSITY

136

770 00440 0490-VHBE

THE CRiSP EDITOR

4. Save your work

2000 ALCATEL BELL N.V. ALL RIGHTS RESERVED

770 00440 0490-VHBE

137

ALCATEL UNIVERSITY

You might also like