You are on page 1of 141

UNIX

(Teach Yourself)

What Is UNIX?
• UNIX is a computer operating system.
• An operating system is the program that controls all the other parts of a computer system,
both the hardware and the software. It allocates the computer's resources and schedules
tasks. It allows you to make use of the facilities provided by the system. Every computer
requires an operating system.
• UNIX is a multi-user, multi-tasking operating system. Multiple users may have multiple
tasks running simultaneously. This is very different than PC operating systems.
• UNIX is a machine independent operating system. Not specific to just one type of
computer hardware. Designed from the beginning to be independent of the computer
hardware.
• UNIX is a software development environment. Was born in and designed to function
within this type of environment.
• The "UNIX" trademark, previously owned by AT&T and then deeded to UNIX Systems
Laboratories (USL), an AT&T subsidiary, passed to Novell when it acquired USL. After
a brief period of negotiations with rival Unix vendors Sun Microsystems, Santa Cruz
Operation, International Business Machines, and Hewlett-Packard, Novell granted
exclusive licensing rights to the UNIX trademark to X/Open Co. Ltd., an Open Systems
industry standards branding agent based in the United Kingdom.

History of UNIX
• 1969: Developed at AT&T Bell Labs in Murray Hill, New Jersey, one of the largest
research facilities in the world. Created in an environment when most computer jobs were
fed into a batch system.

Parimal Sudas Page 1


Developed by researchers who needed a set of computing tools to help them with their
projects and their collaborators. Allowed a group of people working together on a project
to share selected data and programs.

• 1975: AT&T makes UNIX widely available - offered to educational institutions at


minimal cost. Becomes popular with university computer science programs. AT&T
distributes standard versions in source form: Version 6 (1975), Version 7 (1978), System
III (1981).
• 1984 to date: University of California, Berkeley adds major enhancements, creates
Berkeley Standard Distribution (BSD)
• 1984 to date: Many Berkeley features incorporated into new AT&T version: System V
• UNIX has become the operating system of choice for engineering and scientific
workstations.
• Two variations maintain popularity today, AT&T System V based and the Berkeley
Standard Distribution.
• Current versions (1/95)are System V release 4.2 .and 4.4 BSD
• Work is in progress to develop a Portable Operating System specification based on UNIX
(IEEE POSIX committee).

UNIX Philosophy
• Make each program do one thing well. Reusable software tools: 1 tool = 1 function
• Expect the output of every program to become the input of another, yet unknown,
program to combine simple tools to perform complex tasks
• Prototyping: get something small working as soon as possible and modify it
incrementally until it is finished
• Use terse commands and messages: reduces typing and screen output

Why UNIX?
• Hardware independence
o operating system code is written in C language rather than a specific assembly
language
o operating system software can be easily moved from one hardware system to
another
o UNIX applications can be easily moved to other UNIX machines. Porting is
usually as simple as transfer of the source and a recompile
• Productive environment for software development
o rich set of tools
o versatile command language

Parimal Sudas Page 2


• UNIX is available at virtually all HPC centers, allowing researchers relative ease in
utilizing the facilities at each center.
• Distributed processing and multi-tasking

UNIX Components
• Kernel
o The core of the UNIX system. Loaded at system start up (boot). Memory-resident
control program.
o Manages the entire resources of the system, presenting them to you and every
other user as a coherent system. Provides service to user applications such as
device management, process scheduling, etc.
o Example functions performed by the kernel are:
 managing the machine's memory and allocating it to each process.
 scheduling the work done by the CPU so that the work of each user is
carried out as efficiently as is possible.
 accomplishing the transfer of data from one part of the machine to another
 interpreting and executing instructions from the shell
 enforcing file access permissions
o You do not need to know anything about the kernel in order to use a UNIX
system. These details are provided for your information only.
• Shell
o Whenever you login to a Unix system you are placed in a shell program. The
shell's prompt is usually visible at the cursor's position on your screen. To get
your work done, you enter commands at this prompt.
o The shell is a command interpreter; it takes each command and passes it to the
operating system kernel to be acted upon. It then displays the results of this
operation on your screen.
o Several shells are usually available on any UNIX system, each with its own
strengths and weaknesses.
o Different users may use different shells. Initially, your system adminstrator will
supply a default shell, which can be overridden or changed. The most commonly
available shells are:
 Bourne shell (sh)
 C shell (csh)
 Korn shell (ksh)
 TC Shell (tcsh)
 Bourne Again Shell (bash)
o Each shell also includes its own programming language. Command files, called
"shell scripts" are used to accomplish a series of tasks.
• Utilities
o UNIX provides several hundred utility programs, often referred to as commands.
o Accomplish universal functions

Parimal Sudas Page 3


 editing
 file maintenance
 printing
 sorting
 programming support
 online info
 etc.
o Modular: single functions can be grouped to perform more complex tasks

System V vs. BSD


• AT&T distributes System V for their computers. System V is also the basis for several
commercial implementations including:
o Hewlett-Packard HP-UX
o Apple AUX
o Amdahl UTS
o Cray UNICOS
o IBM AIX.
• BSD, from the University of California Berkeley, has undergone extensive modification
and enhancement in the university environment.
• BSD is available directly from UCB and in a number of commercial versions including:
Sun, Apollo, DEC Ultrix, Gould UTX/32.
• System V and BSD contain a large set of commands in common. Some of these
commands, however, support different options and have different default behaviors and
output formats. ex: ls, stty, mail, grep
• Each version also has its own unique utilities. Some very common tasks, such as
browsing a file, are performed by totally different utilities: System V uses "pg" whereas
BSD uses "more".

Logging On To The System


• Before you can begin to use the system you will need to have a valid username and a
password. Assignment of usernames and initial passwords is typically handled by the
System Administrator or a "Computer Accounts" office.
• Your username, also called a userid, should be unique and should not change. Initial
passwords can be anything and should be changed after your first login.
• To login to your account
1. Type your username at the login prompt. UNIX is case sensitive - if your
username is kellyk do not type KellyK . Press the RETURN or ENTER key
after typing your username.

Parimal Sudas Page 4


2. When the password prompt appears, type in your password. Your password is
never displayed on the screen as a security measure. It also is case sensitive. Press
the RETURN or ENTER key after entering your password.
• What happens after you successfully login depends upon your system:

o Many UNIX systems will display a login banner or "message of the day". Make a
habit of reading this since it may contain important information about the system.
o Other UNIX systems will automatically configure your environment and open one
or more windows for you to do work in.
o You should see a prompt - usually a percent sign (%) or dollar sign ($). This is
called the "shell prompt" (the shell is discussed in detail later). It indicates that the
system is ready to accept commands from you.
U If your login attempt was unsuccessful, there are several possible reasons:

1. You made a typing error while entering your username or password


2. The CAPS LOCK key is on and everything is being sent to the system in
uppercase letters.
3. You have an expired or invalid username or password, or the system security has
changed.
4. There are system problems

• Example

• login: kellyk
• kellyk's Password:
• ************************************************************
• * Welcome to the Maui High Performance Computing Center
• ************************************************************
• *
• * Aloha no! (Greetings)
• *
• * System maintenance is scheduled today from 2:00
• * until 4:00 pm HST
• *
• * Mahalo nui loa (Thank you very much)
• *
• ************************************************************

• %

Your Home Directory


• Each user has a unique "home" directory. Your home directory is that part of the file
system reserved for your files.
• After login, you are "put" into your home directory automatically. This is where you start
your work.
Parimal Sudas Page 5
• You are in control of your home directory and the files which reside there. You are also
in control of the file access permissions (discussed later) to the files in your home
directory. Generally, you alone should be able to create/delete/modify files in your home
directory. Others may have permission to read or execute your files as you determine.
• In most UNIX systems, you can "move around" or navigate to other parts of the file
system outside of your home directory. This depends upon how the file permissions have
been set by others and/or the System Administrator, however.

Using UNIX Commands


• UNIX commands are executable files and built-in utility programs
• All UNIX commands are case sensitive. Most commands are in lower case.
• Commands typically have the syntax:

• command option(s) argument(s)

• Options
1. Modify the way that a command works
2. Usually consist of a hyphen followed by a single letter
3. Some commands accept multiple options which can usually be grouped together
after a single hyphen
4. A small number of commands require each option to be given separately
5. Should be separated from the command name by a space
• Arguments
1. Most commands are used together with one or more arguments
2. Some commands assume a default argument if none is supplied
3. Arguments are optional for some commands and required by others
4. In most cases, multiple arguments should be separated from each other by a
space. They should be separated from the command name and/or options by a
space also.
• Examples
1. To use a command with no argument: the "date" command displays the current
time and date.

date

2. To use a command with a single argument: the "cd" command changes to the
directory of its argument, newdir

cd newdir

Parimal Sudas Page 6


3. To use a command with both an option and an argument: the wc command counts
the number of words, characters, and lines in a file. By using a different option
you can choose what is counted.
4.
5. wc -w file1 counts the words in file1
6. wc -c file1 counts the characters in file1
7. wc -l file1 counts the lines in file1

8. To use a command with several arguments: the cat command takes the names of
three files as arguments. It prints file1 followed by file2 and then file3 on the
screen.

cat file1 file2 file3

9. To use a command with multiple options and default argument: the ls command
provides a long (l) listing of all (a) files and also shows the file size (s). Because
no argument is specified, the default argument (current directory) will be used.

ls -als

• Multiple commands can be entered on one line if you separate each with a semicolon. For
example: this command line contains two commands. The first, cd newdir changes the
current directory to the directory newdir. The second, ls -l produces a long listing of the
contents of the newdir directory.

cd newdir ; ls -l

• Commands can continue beyond one line by using a backslash (\) character. For example:
this command copies the file called recipe from kelly's home directory to the current
directory and renames it kelly.recipe. It then sends this file to the printer ps3 with the
request that 6 copies be printed.

• cp /users/kelly/recipe kelly.recipe ; \
• lpr -Pps3 #6m kelly.recipe

Special Characters
• The UNIX shell interprets a number of characters in special ways. These characters are
most often used with UNIX commands - as arguments and for other means. The
following list contains most of UNIX's special characters

• NEWLINE - initiates command execution
• ; - separates commands on same line
• ( ) - groups commands or identifies a function

Parimal Sudas Page 7


• & - executes a command in the background
• | - pipe
• > - redirects standard output
• >> - appends standard output
• < - redirects standard input
• * - wildcard for any number of characters in a
• file name
• ? - wildcard for a single character in a file
• name
• \ - quotes the following character
• ' - quotes a string preventing all substitutions
• " - quotes a string allowing variable and
• command substitution
• ` - performs command substitution
• [ ] - denotes a character class in a file name
• $ - references a variable
• { } - command grouping within a function
• . - executes a command (if at beginning of line)
• # - begins a comment
• : - null command

• Examples
1. Use the * character in file names to match any number of characters. The
following command:

ls *.txt

Will match the following files:

chapter1.txt doc.txt memo.txt a.txt

Will not match the following files:

doctxt txt.memo

2. Use the ? character in file names to match any single character. The following
command:

ls ???.txt

Will match the following files:

one.txt doc.txt two.txt

Will not match the following files:

chap1.txt doctxt

Parimal Sudas Page 8


3. Use the [ ] characters in file names to match any character within a range of
characters. The following command:

ls chapter[1-3].txt

Will match the following files:

chapter1.txt chapter2.txt chapter3.txt

Will not match the following files:

chap1.txt chapter4.txt

• Other uses for special characters and examples will be discussed later.

Terminal Control Keys


• Several key combinations on your keyboard usually have a special effect on the terminal.
• These "control" (CTRL) keys are accomplished by holding the CTRL key while typing
the second key. For example, CTRL-c means to hold the CTRL key while you type the
letter "c".
• The most common control keys are listed below:

• CTRL-u - erase everything you've typed on the command
• line

• CTRL-c - stop/kill a command

• CTRL-h - backspace (usually)

• CTRL-z - suspend a command

• CTRL-s - stop the screen from scrolling

• CTRL-q - continue scrolling

• CTRL-d - exit from an interactive program (signals end
• of data)

Changing Your Password


• Your password is important; it stops other users from gaining access to your account.
Never give your password to anyone

Parimal Sudas Page 9


• You should change your initial password very soon after your first login
• To change your password: enter the command passwd and then respond to the prompts
by entering your old password followed by your new one. You are then asked to retype
your password for confirmation.

Note that what you type will not appear on the screen for security reasons. For example:

passwd
Old password: - enter your current password
New password: - enter your new password
Retype new password: - re-enter your new password

If you make a mistake, the message: Mismatch - password unchanged. is


displayed and your password remains unchanged. Try again.

• Guidelines for creating a password

Don't

o choose a word from a dictionary


o use personal information such as your name, make of car, pet, sweetheart, etc.
o tell anyone your passwd
o write your password down anywhere
o keep the password you were given when you first got your userid

Do

o choose an obscure password preferably between 6 and 8 characters in length, of


mixed case and containing at least one non-alphanumeric character such as ! or @
o change your password at regular intervals
• Keep in mind that there are people who think it's fun to "crack" passwords and get into
other people's accounts. There are plenty of easily available "cracking" programs which
make guessing easy passwords a cinch.

Getting Information
• The "man" command
o The "man" command man gives you access to an on-line manual which
potentially contains a complete description of every command available on the
system. In practice, the manual usually contains a subset of all commands.
o man can also provide you with one line descriptions of commands which match a
specified keyword

Parimal Sudas Page 10


o The online manual is divided into sections:
o
o Section Description
o ------- -----------
o 1 User Commands
o 2 System Commands
o 3 Subroutines
o 4 Devices
o 5 File Formats
o 6 Games
o 7 Miscellaneous
o 8 System Administration
o l Local Commands
o n New Commands

o Examples of using the man command:


1. To display the manual page for the cp (copy files) command:

man cp

--More--23% at the bottom left of the screen means that only 23% of
the man page is displayed. Press the space bar to display more of it or type
q to quit.

2. By default, the man page in section 1 is displayed if multiple sections


exist. You can access a different section by specifying the section. For
example:

man 8 telnetd

3. Keyword searching: use the -k option followed by the keyword. Two


examples appear below.
4.
5. man -k mail
6. man -k 'copy files'

7. To view a one line description of what a command does:

whatis more

will display what the "more" command does:

more, page (1) - browse or page through a text


file

• who - shows who is on the system


Parimal Sudas Page 11


• who
• who am i

• finger - displays information about users, by name or login name



• finger doe
• finger userid

Logging Off The System


• To finish using a UNIX system you must go through a process known as "logging out" or
"logging off".
• To logout enter the command logout or exit. If this does not, work press Ctrl-d.
• If you have a .logout file in your home directory, the system will execute any commands
contained there.
• Problems
1. If you see the message There are stopped jobs it is a warning which
tells you that there is a job which you suspended earlier (Ctrl-z) or a job running
in the background (discussed later).

The simplest way to accomplish the logout is to just issue the logout command
again. Your suspended/background jobs will be terminated and you will be logged
off the system.

2. If you see the message Not login shell it means you are working in
another "shell" that has been started from within your "login shell" (shells will be
discussed later).

To logout, issue the exit command and then try to logout again.

Introduction to UNIX
Getting Started Exercises
Logging On To The System
The details of logging in to a UNIX computer will differ from system to system. The steps covered here
are specific for the MHPCC classroom.

1. The instructor will assign every student a unique userid and password. Make sure you know
yours before proceeding. The instructor will also show you how to setup your terminal for
logging on.
Parimal Sudas Page 12
2. After your computer terminal is ready for logging on, review the screen and look for a place to
type in your userid and password.
3. Type in your userid, making sure that you distinguish between uppercase and lowercase letters
as required. Press the return key when finished.
4. Type in your password, also making sure that you distinguish between uppercase and lowercase
letters as required. It will not appear as you type for security reasons. Press the return key when
finished.
5. If you are unsuccessful at logging in, the system will give you another try. Keep trying until you
succeed. If you don't succeed after 5 tries, call the instructor.
6. After you have successfully logged in, the system will automatically create your initial
environment including a clock and a window for entering commands.
7. Notice the window - it should ask you which type of session you want. Answer the prompt by
typing in the number which matches: Introduction to UNIX. You will then be prompted to "start
Netscape" - type y for yes.
8. After a few seconds, you should see the Introduction to UNIX window. If you do not, call the
instructor.
9. Return to the tutorial to learn about the next section before proceeding.

Using UNIX Commands


This exercise will familiarize you with the basics of issuing UNIX commands.

1. You should still have a window on your screen from the previous exercise. Select that window
by dragging the mouse pointer into the window and then clicking with the left mouse button.
The window is now ready to accept input from you.
2. Try a few simple commands which require no arguments or options:
3.
4. date - show date and time
5. whoami - show your userid
6. who - show who is logged onto the system
7. w - show who is logged onto the system
8. pwd - print the working directory's name
9. clear - clear the screen

10. Now try some commands which require arguments and/or options:
11.
12. ls -a - list all files in current directory
13. ls -al - long list of current directory
14. cat .cshrc - display contents of .cshrc file
15. mkdir dir1 - make a directory called dir1
16. cd dir1 - change directory to dir1
17. cd .. - change to parent directory
18. rmdir dir1 - remove directory dir1
19. cp .login new.login - copy the .login file to new.login
20. wc new.login - count the lines, words and
21. characters in the new.login file
22. wc -l new.login - count just the lines
23. rm new.login - remove the new.login file
24.

Parimal Sudas Page 13


25. Try using multiple commands on one line. Don't forget to include the semi-colon between
commands.
26.
27. cp .login testfile ; cat testfile
28. - copy a file and then show its contents
29.
30. ls -l testfile ; rm testfile ; ls -l testfile
31. - list (long) a file, remove it, and then try to
32. list it again

33. Return to the tutorial to learn about the next section before proceeding.

Special Characters
This exercise will acquaint you with the use of several of the UNIX special characters.

1. First, make sure you are in your home directory (issue the "cd" command with no arguments).
Now "cd" to this exercise's subdirectory by using the command:
2.
3. cd GetStart

4. Using the "*" wildcard character, list all of the files in this subdirectory:
5.
6. ls *

7. Using the "?" wildcard character, list all files with 3 character names:
8.
9. ls ???

10. Using square brackets and wildcard characters, try listing files several different ways:
11.
12. ls [a-c]*
13. ls [abcde]*
14. ls [a-z]*
15. ls [z]*
16. ls ??[c]*
17. ls ?[e]*

18. Using the right angle bracket ">" and the semi-colon ";", concatenate three files into a single
new file and then display it:
19.
20. cat alpha beta gamma > newfile ; cat newfile

Parimal Sudas Page 14


21. Return to the tutorial to learn about the next section before proceeding.

Terminal Control Keys


This exercise will familiarize you with several of the terminal control keys used by UNIX.

1. Erasing the command line: At the command prompt, begin typing several characters. It doesn't
matter what you type (but don't press the Return key) because you will then erase the line by
typing CTRL-u.
2. Killing a command: Start the command sleep 300 which simply "sleeps" for 300 seconds.
After it is started, try using another UNIX command such as "ls". What happens? Kill the sleep
process by using CTRL-c, and try it again. What happens now?
3. Backspacing: At the command prompt, begin typing several characters. It doesn't matter what
you type (but don't press the Return key). After typing several characters, try using CRTL-h to
backspace. Most keyboards will allow you to backspace by using a "backspace" or "delete" key
also.
4. Screen Scrolling: Issue a command which will send lots of information to the screen: ls -R /
While the information is being displayed, use CTRL-s to stop it and then CTRL-q to restart it. Try
CTRL-s and CTRL-q a couple times. Then kill the process with CTRL-c.
5. Return to the tutorial to learn about the next section before proceeding.

Changing Your Password


This exercise will familiarize you with changing your password on a UNIX system.

1. Each student should have received an initial password from the instructor. If you are not sure of
yours, ask the instructor.
2. Think of a new password which follows the guidelines mentioned in the tutorial. Remember
what it is.
3. Change your initial password by issuing the passwd command. As your are prompted, supply
your old password and then your new password. You will be asked to type the new password
twice for confirmation. Notice that nothing appears on the screen as you type.
4. Now change your password back to the original password. Please don't forget to do this step!
5. Return to the tutorial to learn about the next section before proceeding.

Getting Information
This exercise will familiarize you with several different UNIX utilities for obtaining information about the
system.

1. Use the man command to read in depth about some common UNIX utilities:
2.
3. man ls
4. man cp
5. man rm
6. man man

Parimal Sudas Page 15


7. Use the following commands to find out about users on the system, including yourself:
8.
9. who
10. whoami
11. who am i
12. finger
13. finger your userid

14. Return to the tutorial to learn about the next section before proceeding.

Logging Off The System


This exercise will familiarize you with logging off a UNIX system - in particular, an MHPCC training
system. Note that this procedure may differ from system to system.

1. In your open window, type either of the following commands to logout:


2.
3. logout
4. exit

5. This will cause your window to disappear. In other UNIX systems, without a windows
environment, these same commands would terminate your entire session.

Hierarchical File Structure


• All of the files in the UNIX file system are organized into a multi-leveled hierarchy
called a directory tree.
• A family tree is an example of a hierarchical structure that represents how the UNIX file
system is organized. The UNIX file system might also be envisioned as an inverted tree
or the root system of plant.
• At the very top of the file system is single directory called "root" which is represented by
a / (slash). All other files are "descendents" of root.
• The number of levels is largely arbitrary, although most UNIX systems share some
organizational similarities. The "standard" UNIX file system is discussed later.
• Example:

• / (root)
• |
• ---------------------
• | | |
• /bin /usr /tmp
• |
• |

Parimal Sudas Page 16


• -------------------
• | | |
• /public /misc /staff
• | |
• ------------ -------------------
• | | | | | |
• /software /doc /john /mary /bill /carl

File Types
The UNIX filesystem contains several different types of files:

• Ordinary Files
o Used to store your information, such as some text you have written or an image
you have drawn. This is the type of file that you usually work with.
o Always located within/under a directory file
o Do not contain other files
• Directories
o Branching points in the hierarchical tree
o Used to organize groups of files
o May contain ordinary files, special files or other directories
o Never contain "real" information which you would work with (such as text).
Basically, just used for organizing files.
o All files are descendants of the root directory, ( named / ) located at the top of the
tree.
• Special Files
o Used to represent a real physical device such as a printer, tape drive or terminal,
used for Input/Ouput (I/O) operations
o Unix considers any device attached to the system to be a file - including your
terminal:
 By default, a command treats your terminal as the standard input file
(stdin) from which to read its input
 Your terminal is also treated as the standard output file (stdout) to which a
command's output is sent
 Stdin and stdout will be discussed in more detail later
o Two types of I/O: character and block
o Usually only found under directories named /dev
• Pipes
o UNIX allows you to link commands together using a pipe. The pipe acts a
temporary file which only exists to hold data from one command until it is read
by another
o For example, to pipe the output from one command into another command:
o
o who | wc -l

Parimal Sudas Page 17


This command will tell you how many users are currently logged into the system.
The standard output from the who command is a list of all the users currently
logged into the system. This output is piped into the wc command as its standard
input. Used with the -l option this command counts the numbers of lines in the
standard input and displays the result on its standard output - your terminal.

File Names
• UNIX permits file names to use most characters, but avoid spaces, tabs and characters
that have a special meaning to the shell, such as:

• & ; ( ) | ? \ ' " ` [ ] { } < > $ - ! /

• Case Sensitivity: uppercase and lowercase are not the same! These are three different
files:

• NOVEMBER November november

• Length: can be up to 256 characters


• Extensions: may be used to identify types of files

• libc.a - archive, library file
• program.c - C language source file
• alpha2.f - Fortran source file
• xwd2ps.o - Object/executable code
• mygames.Z - Compressed file

• Hidden Files: have names that begin with a dot (.) For example:

• .cshrc .login .mailrc .mwmrc

• Uniqueness: as children in a family, no two files with the same parent directory can have
the same name. Files located in separate directories can have identical names.
• Reserved Filenames:

• / - the root directory (slash)
• . - current directory (period)
• .. - parent directory (double period)
• ~ - your home directory (tilde)

Parimal Sudas Page 18


Pathnames
• Specify where a file is located in the hierarchically organized file system
• Must know how to use pathnames to navigate the UNIX file system
• Absolute Pathname: tells how to reach a file begining from the root; always begins with /
(slash). For example:

• /usr/local/doc/training/sample.f

• Relative Pathname: tells how to reach a file from the directory you are currently in
( current or working directory); never begins with / (slash). For example:

• training/sample.f
• ../bin
• ~/projects/report.001

• For example, if your current directory is /usr/home/johnson and you wanted to change to
the directory /usr/home/quattro, you could use either of these commands:

• cd ../quattro - relative pathname
• cd /usr/home/quattro - absolute pathname

File and Directory Commands


UNIX provides a number of commands for working with files. The more common ones are
described in this section. Note that these commands usually have several options and accept
wildcard characters as arguments. For details, see the respective man pages which are
hyperlinked to each command name.

• ls - lists files

• ls - show contents of working directory
• ls file - list file, if it exists in working directory
• ls dir - show contents of the directory dir
• ls -a - shows all your files, including hidden ones
• ls -al - give detailed listing of contents
• ls -F - mark directories with "/" and executable
• files with "*"
• ls *.doc - show all files with suffix ".doc"

• more - browses/displays files one screen at a time. Use h for help, spacebar to page, b for
back, q to quit, /string to search for string
Parimal Sudas Page 19

• more sample.f

• pg - browses/displays files one screen at a time. Similar to the more utility in function but
has different commands and options. See the man page for details.

• pg sample.f

• less - similar to more, but with more features. Not available on every system.

• less sample.f

• head - displays the first n lines of a file



• head sample.f - display first 10 lines (default)
• head -5 sample.f - display first 5 lines
• head -25 sample.f - display first 25 lines

• tail - displays the last n lines or n characters of a file



• less sample.f - display last 10 lines (default)
• less -5 sample.f - display last 5 lines
• less -5c sample.f - display last 5 characters
• less -25 sample.f - display last 25 lines

• cat - dumps the entire file to the screen without paging. This command is more useful for
concatenating (hence the name "cat") files together than it is for reading files.

• cat myprog.c - diplays entire file
• cat -b myprog.c - shows line numbers
• cat file1 file2 > file3 - adds file1 and file2 to make
• file3

• cp - copies files. Will overwrite unless otherwise specified. Must also have write
permission in the destination directory.

• cp sample.f sample2.f - copies sample.f to sample2.f
• cp -R dir1 dir2 - copies contents of directory
• dir1 to dir2
• cp -i file.1 file.new - prompts if file.new will be
• overwritten
• cp *.txt chapt1 - copies all files with .txt
• suffix to directory chapt1

Parimal Sudas Page 20


• cp /usr/doc/README ~ - copies file to your home
• directory
• cp ~betty/index . - copies the file "index" from
• user betty's home directory
• to current directory

• mv - moves files. Will overwrite unless otherwise specified. Must also have write
permission in the destination directory.

• mv sample.f sample2.f - moves sample.f to sample2.f
• mv dir1 newdir/dir2 - moves contents of directory
• dir1 to newdir/dir2
• mv -i file.1 file.new - prompts if file.new will be
• overwritten
• mv *.txt chapt1 - moves all files with .txt
• suffix to directory chapt1

• rm - deletes/removes files or directories if file permissions permit.



• rm sample.f - deletes sample.f
• rm chap?.txt - deletes all files with chap as the
• first four characters of their name
• and with .txt as the last four
• characters of their name
• rm -i * - deletes all files in current directory
• but asks first for each file
• rm -r /olddir - recursively removes all files in the
• directory olddir, including the
• directory itself

• file - identifies the "type" of file. The command syntax is:



• file filename

For example:

file * - reports all files in current


directory and their types. The
output might appear as shown below:

about.html: ascii text


bin: directory
staff.directory: English text
bggen: executable or object module not stripped
bmbinc: commands text

Parimal Sudas Page 21


machines.sp1: [nt]roff, tbl, or eqn input text
man2html: executable or object module not stripped
man2html.c: ascii text

• find - finds files. The syntax of this command is:



• find pathname -name filename -print

The pathname defines the directory to start from. Each subdirectory of this directory will
be searched.

The -print option must be used to display results.

You can define the filename using wildcards. If these are used, the filename must be
placed in 'quotes'.

find . -name mtg_jan92 -print - looks for the file


mtg_jan92 in current
directory
find ~/ -name README -print - looks for files called
README throughout your
home directory
find . -name '*.fm' -print - looks for all files with
.fm suffix in current
directory
find /usr/local -name gnu -type d -print
- looks for a directory
called gnu within the
/usr/local directory

• diff - comparing two files or directories. Indicates which lines need be added (a), deleted
(d) or changed (c). Lines in file1 are identified with a (<) symbol: lines in file2 with a (>)
symbol

• diff file1 file2 - compares file1 to file2
• diff -iw file1 file2 - compares two files ignoring
• letter case and spaces
• diff dir1 dir2 - compares two directories
• showing files which are
• unique to each and also,
• line by line differences
• between any files in common.

For example, if file1 and file2 are:

Parimal Sudas Page 22


John erpl08@ed John erpl08@ed
Joe CZT@cern.ch Joe CZT@cern.ch
Kim ks@x.co Jean JRS@pollux.ucs.co
Keith keith@festival Jim jim@frolix8
Kim ks@x.co
Keith keith@festival

Using the diff command: diff file1 file2 Yields the output:

2a3,4
> Jean JRS@pollux.ucs.co
> Jim jim@frolix8

Which means that to make these files match you need to add (a) lines 3 and 4 (3,4) of
file2 (>) after line 2 in file1.

• sdiff - similar to diff, but displays each line of the two files side by side, making it easier
for you to see the differences between them

Lines that are different are shown with a | symbol. Lines unique to file1 are identified by
a < symbol; lines unique to file2 with a > symbol. Identical lines appear next to each
other. The option -w 80 is used to set the width of the output from the command to 80
characters. The default is 130 characters.

sdiff -w 80 file1 file2


Mike erpl08@ed | John erpl08@ed
Joe CZT@cern.ch Joe CZT@cern.ch
> Jean JRS@pollux.ucs.co
> Jim jim@frolix8
Kim ks@x.co Kim ks@x.co
Sam s.wally@aston <
Keith keith@festival Keith keith@festival

• ln - link one file name to another. The command syntax is:



• ln source linkname

Making a link to a file or directory does not create another copy of it. It simply makes a
connection between the source and the linkname. Allows a single file to be "pointed to"
by other filenames without having to duplicate the file.

ln results.1 last.run - links filename "last.run" to


the real file results.1 in

Parimal Sudas Page 23


the current directory.
ln notes ../Notes.jan - links filename "notes" in
current directory to real file
Notes.jan in parent directory.

• sort - sorts files, merges files that are already sorted, and checks files to determine if they
have been sorted. The command syntax is:

• sort options filename

By default, lines in "filename" are sorted and displayed to the screen. If the "filename"
parameter specifies more than one file, the sort command concatenates the files and sorts
them as one file.

An output file can be specified with the -o flag.

Files can be sorted by "fields" - single or multiple.

The sort command supports many options. See the man page for details.

sort addresses - sorts the file


addresses and displays
output on screen
sort -o sorted addresses - sorts the file
addresses and writes
output to the file
called sorted.
sort -u -o mail_labels addresses - removes all duplicate
lines from the file
addresses and writes
the output in the
file mail_labels.
sort +2 -4 addresses - sorts the file by
its third and fourth
fields. Note that
+2 means to skip first
two fields and -4
means to stop after
the fourth field.

Continue the Filesystem exercises - Part 2.

• pwd - print working directory. Tells you which directory you are currently in.

• pwd

Parimal Sudas Page 24


• mkdir - make directory. Will create the new directory in your working directory by
default.

• mkdir /u/training/data
• mkdir data2

• cd - change to specified directory. May specify either the absolute or relative pathname.
cd with no pathname changes to your home directory.

• cd /usr/local - change to /usr/local
• cd doc/training - change to doc/training in current
• directory
• cd .. - change to parent directory
• cd ~/data - change to data directory in
• home directory
• cd ~joe - change to user joe's home directory
• cd - change to home directory

• rmdir - remove directory. Directories must be empty before you remove them.

• rmdir project1

To recursively remove nested directories, use the rm command with the -r option:

rm -r dirctory_name

• A summary of commands and utilities related to the UNIX file system appears below.
See the corresponding man pages for detailed information.

• awk -search for and process patterns in a file,
• cat -display, or join, files
• cd -change working directory
• chgrp -change the group that is associated with a file
• chmod -change the access mode of a file
• chown -change the owner of a file
• comm -compare sorted files
• cp -copy files
• df -display the amount of available disk space
• diff -display the differences between two files
• du -display information on disk usage
• file -display file classification
• find -find files
• fsck -check and repair a file system
• grep -search for a pattern in files

Parimal Sudas Page 25


• head -display the first few lines of a file
• ln -create a link to a file
• lp -print files (System V)
• lpr -print files (Berkeley)
• ls -list information about files
• mkdir -create a directory
• more -display a file one screen at a time (System V)
• mv -move and/or rename a file
• od -dump a file
• pg -display a file one screen at a time (Berkeley)
• pr -paginate a file
• pwd -print the working directory
• rm -remove (delete) files
• rmdir -remove (delete) a directory
• sed -stream editor (non-interactive)
• sort -sort and/or merge files
• spell -check a file for spelling errors
• tail -display the last few lines of a file
• tar -store or retrieve files from an archive file
• umask -set file creation permissions
• uniq -display the lines in a file that are unique
• wc -counts lines, words and characters in a file
• whatis -list man page entries for a command
• whereis -show where executable is located in path
• which -locate an executable program using "path"

Access Permissions
• UNIX is a multi-user system. Every file and directory in your account can be protected
from or made accessible to other users by changing its access permissions. Every user has
responsibility for controlling access to their files.
• Permissions for a file or directory may be any or all of:

• r - read
• w - write
• x - execute = running a program

• Each permission (rwx) can be controlled at three levels:



• u - user = yourself
• g - group = can be people in the same project
• o - other = everyone on the system

Parimal Sudas Page 26


• File access permissions are displayed using the ls -l command. The output from the ls -l
command shows all permissions for all levels as three groups of three according to the
scheme:

• owner read (r)
• owner write (w)
• owner execute (x)
• group read (r)
• group write (w)
• group execute (x)
• public read (r)
• public write (w)
• public execute (x)

• which are displayed as: -rwxrwxrwx

Example outputs from the ls -l command:

-rw------- 2 smith staff 3287 Apr 8 12:10 file1


- User has read and write permission. Group and
others have no permissions.

-rw-r--r-- 2 smith staff 13297 Apr 8 12:11 file2


- User has read and write permission. Group and
others can only read the file.

-rwxr-xr-x 2 smith staff 4133 Apr 8 12:10 myprog


- User has read, write and execute permission.
Group and others can read and execute the file.

drwxr-x--- 2 smith staff 1024 Jun 17 10:00 SCCS


- This is a directory. The user has read, write and
execute permission. Group has read and execute
permission on the directory. Nobody else can
access it.

• Note: a directory must have both r and x permissions if the files it contains are to be
accessed.
• The chmod command is used to change access permissions for files which you own. The
syntax is:

• chmod permission_triads filename
• [who][action][permissions]

where:

Parimal Sudas Page 27


who action permissions

u = user + = add r = read


g = group - = remove w = write
o = other x = execute
a = all

Examples:

chmod a+r sample.f


- Adds read permission for all users to the file
sample.f.

chmod o-r sample.f


- Removes read permission for others to the file
sample.f.

chmod og+rx prog*


- Adds read and execute permissions for group and
others to all files which contain "prog" as the
first four characters of their name.

chmod +w *
- Adds write permission for user to all files in
current directory.

• File access permissions can also be changed by a numerical (octal) chmod specification.
Read permission is given the value 4, write permission the value 2 and execute
permission 1.

• r w x
• 4 2 1

These values are added together for any one user category:

0 = no permissions
1 = execute only
2 = write only
3 = write and execute (1+2)
4 = read only
5 = read and execute (4+1)
6 = read and write (4+2)
7 = read and write and execute (4+2+1)

So access permissions can be expressed as three digits. For example:

Parimal Sudas Page 28


user group others

chmod 640 file1 rw- r-- ---


chmod 754 file1 rwx r-x r--
chmod 664 file1 rw- rw- r--

• Never set write permission for all other users on a file or directory which is in your home
directory. If you do other users will be able to change its content. This can represent a
serious security risk.
• The umask command is used to set your default file permissions. Typically, the umask
command is included as part of your .profile, .cshrc or .login file.

The umask command accepts only octal specifications. Note that these are different than
those used by the chmod command, and in fact, represent which permissions to "mask
out", or remove.

Octal number Access permissions given


0 rwx read, write and
execute
1 rw- read and write
2 r-x read and execute
3 r-- read only
4 -wx write and execute
5 -w- write only
6 --x execute only
7 --- no permissions

Example umask commands:

umask 077
- Subtracts 077 from the system defaults for files
(666) and directories (777). Results in default
access permissions for your files of 600
(rw-------) and for directories of 700
(rwx------).

umask 002
- Subtracts 002 from the sytem defaults to give a
default access permission for your files of 664
(rw-rw-r--) and for your directories of 775
(rwxrwxr-x).

umask 022
- Subtracts 022 from the system defaults to give a
default access permission for your files of 644
(rw-r--r--) and for your directories of 755
(rwxr-xr-x).

Parimal Sudas Page 29


Standard UNIX File System
• There is no single standard UNIX file structure. Most UNIX systems however, follow a
general convention for filesystem organization at the highest level.

• /(root) - The top level directory referred to as root.
• Contains all files in the file system.

• /bin - Executable files for standard UNIX
• utilities

• /dev - Files that represent input/output devices

• /etc - Miscellaneous and system administrative
• files such as the password file and system
• start up files.

• /lib - UNIX program libraries

• /tmp - Temporary space that can be used by
• programs or users.

• /usr/bin - More UNIX utilities. By convention /bin
• contains standard utilities and /usr/bin
• contains less common utilities.

• /usr/bin/X11 - X windows binaries

• /usr/lib - More UNIX libraries

• /usr/lib/X11 - X windows libraries

• /usr/local - Programs installed by local site

• /usr/ucb - Berkeley utilities

• /u - User home directories

• /var - Variable sized files - can grow and
• shrink dynamically, such a users mail
• spool and print spool files.

Introduction to UNIX
Filesystem Exercises
Parimal Sudas Page 30
These exercises will familiarize you with the basic UNIX commands for working with files and filesystems.

Setup

1. Open a new window or use an existing open window. To open a new window, press and hold
the right mouse button. A "pop up" menu will appear. Still holding the right mouse button, drag
the pointer to the selection which says "New Window". When it is selected (the item will appear
highlighted or raised), release the right button. A new window will appear in a second or two.
2. Change to this exercise's subdirectory by using the command:
3.
4. cd ~/Filesystem

5. Begin the Filesystem exercises with the ls exercise below.

ls

1. Read/scan the man page for ls with the command:


2.
3. man ls

4. Use ls without any arguments to display this directory's contents. How many files do you see?
5. Now use ls with the -a option. How many files do you see this time? Notice that the "new" files
all begin with a "dot", which indicates they are "hidden" files.
6.
7. ls -a

8. This command is useful for distinguishing between directories, ordinary files, and executable
files. Notice how its output differs from ls without arguments.
9.
10. ls -F

11. Use the command ls -l to obtain a "long" listing of your files. Sample output from this command
and an explanation of the information it provides appears below.
12.
13. -rwxr-xr-x 1 jsmith staff 43 Mar 23 18:14 prog1
14. -rw-r--r-- 1 jsmith staff 10030 Mar 22 20:41 sample.f
15. drwxr-sr-x 2 jsmith staff 512 Mar 23 18:07 subdir1
16. drwxr-sr-x 2 jsmith staff 512 Mar 23 18:06 subdir2
17. drwxr-sr-x 2 jsmith staff 512 Mar 23 18:06 subdir3
18. 1 2 3 4 5 6 7
19.
20. 1 = access modes/permissions
21. 2 = number of links
22. 3 = owner
23. 4 = group

Parimal Sudas Page 31


24. 5 = size (in bytes)
25. 6 = date/time of last modification
26. 7 = name of file

27. Recursive listings can be very useful. Try both of the commands below. What does the output
tell you?
28.
29. ls -R
30. ls -Rl

31. Try three options together:


32.
33. ls -lFa

more

1. Read/scan the man page for more with the command:


2.
3. man more

4. Use the more command to read a file:


5.
6. more nasa.94

7. As you are reading, notice the "More" prompt at the bottom of the page.
8. Try pressing the return key - what happens?
9. Try pressing the space bar once - what happens?
10. Type the letter b - what happens?
11. Use the search forward feature to find the word "MARCH" by entering the command:
12.
13. /MARCH

14. Now use the search backward feature to find the words "black hole" by entering the command:
15.
16. ?black hole

17. more will continue until the end of the file is reached or until you type q for quit. Try typing q to
quit.

head and tail

1. Read/scan the man page for head with the command:


Parimal Sudas Page 32
2.
3. man head

4. Display the top of a file with the command below. How many lines do you count?
5.
6. head nasa.94

7. Now try this command and note how many lines are displayed this time?
8.
9. head -5 nasa.94

10. Read/scan the man page for tail with the command:
11.
12. man tail

13. Display the same file with the tail command. How is it different and how many lines do you
count?
14.
15. tail nasa.94

16. Now try this command and note how many lines are displayed this time?
17.
18. tail -5 nasa.94

cat

1. Read/scan the man page for cat with the command:


2.
3. man cat

4. Use this command to display the contents of a file. What happens?


5.
6. cat nasa.94

7. Now try this command notice the difference. How many lines are in the file?
8.
9. cat -n nasa.94

10. The cat command is more often used for purposes other than just displaying a file. Try these
commands to "concatenate" two files into a new, third file:
11.
12. cat file1 - first, show file1

Parimal Sudas Page 33


13. cat file2 - then, show file2
14. cat file1 file2 > newfile - now do the actual concatenate
15. cat newfile - finally, show the result

cp

1. Read/scan the man page for cp with the command:


2.
3. man cp

4. Copy an existing file in your current directory to another file in the current directory and then
list your directory to prove that it was done:
5.
6. cp sample.f sample2.f
7. ls

8. Copy a file from a different directory to your current directory and then list your directory to
prove that it was done:
9.
10. cp /etc/environment my.environment
11. ls

12. Use the copy command with the "inquire" option. What happens?
13.
14. cp -i sample.f sample2.f

15. Use the recursive option to copy an entire subdirectory to a new subdirectory and then list both
directories to prove that it worked:
16.
17. cp -R subdir1 subdir4
18. ls subdir1 subdir4

19. The copy command accepts "wildcard" characters. Try the command below. What did it do? List
the subdir1 subdirectory to find out.
20.
21. cp samp* subdir1
22. ls subdir1

23. If you are copying a file from another location to the current directory and want its name to
remain the same, you can use the shorthand "." to indicate the current directory. Try this for
example and note what happens:
24.
25. cp /etc/environment .
26. ls

Parimal Sudas Page 34


mv

1. Read/scan the man page for mv with the command:


2.
3. man mv

4. The mv command can be used for renaming files. Try this command and then list your files to
prove that the command worked:
5.
6. mv sample2.f new.sample
7. ls

8. mv can be used to rename directories also. Try this command and then list your files to prove
that the command worked:
9.
10. mv subdir4 dir4
11. ls

12. The mv command is also used for moving files. Use the command below to move new.sample
into a new location, then list your files to prove that the command worked:
13.
14. mv new.sample dir4
15. ls
16. ls dir4

17. Like many other UNIX commands, mv recognizes wildcard characters. Try the command below
and then list your files to prove that the command worked:
18.
19. mv *env* dir4
20. ls
21. ls dir4

rm

1. Read/scan the man page for rm with the command:


2.
3. man rm

4. Use the rm command to delete a file. List your directory after the command completes.
5.
6. rm sample.f
7. ls

Parimal Sudas Page 35


8. cd to the subdir2 subdirectory. List the directory to view its contents. Then use the "*" wildcard
to remove all of the files. NOTE: using rm in this manner can be dangerous! If you are in the
wrong directory, you'll remove files you didn't mean to remove. You may want to use the -i
option to protect yourself from accidents.
9.
10. cd subdir2
11. ls
12. rm -i *
13. ls

14. Get out of the subdir2 subdirectory by using the command cd .. Now try to use rm to remove a
directory. What happens?
15.
16. cd ..
17. rm subdir3

18. This time, include the -r option when you try to remove a directory. What happens?
19.
20. rm -r subdir3
21. ls

22. Return to the tutorial to learn about the next section before proceeding.

file

1. Read/scan the man page for file with the command:


2.
3. man file

4. Use the file command to determine a file's type:


5.
6. file file1

7. Now try it with a directory:


8.
9. file dir4

10. Finally, try it with a wildcard character;


11.
12. file *

Parimal Sudas Page 36


find

1. Read/scan the man page for find with the command:


2.
3. man find

4. Use the find command to find the file new.sample.


5.
6. find . -name new.sample -print

7. Now use the find command to find all files with "file" as part of their name. Don't forget to put
the wildcard specification in quotes - it won't work otherwise:
8.
9. find . -name 'file*' -print

10. Try to find only directories with "file" as part of their name. Are there any?
11.
12. find . -name 'file*' -type d -print

diff and sdiff

1. Read/scan the man page for diff with the command:


2.
3. man diff

4. Use the diff command to determine the differences between two files:
5.
6. diff names1 names2

7. Use the diff command to determine the differences between two directories.
8.
9. diff subdir1 dir4

10. Try using sdiff to display the differences between names1 and names2:
11.
12. sdiff names1 names2

13. Now try sdiff specifying that the screen width is 80 characters...not the default 130:
14.
15. sdiff -w 80 names1 names2

Parimal Sudas Page 37


ln

1. Read/scan the man page for ln with the command:


2.
3. man ln

4. Create a link between two files in the same directory. Use ls -l to list your directory afterwards
to confirm that the link was done:
5.
6. ln names1 linknames
7. ls -l

8. Create a link between two files in different filesystems. Note that you'll need the -s option to
accomplish this. Use ls -l to list your directory afterwards to confirm that the link was done.
Notice how the link is identified in the listing.
9.
10. ln -s /etc/environment myenv
11. ls -l

12. Use the rm command to remove both of the links. Note that the original files will not be
affected.
13.
14. rm linknames
15. rm myenv
16. ls -l

sort

1. Read/scan the man page for sort with the command:


2.
3. man sort

4. Use the cat command to look at an unsorted list of names. Notice that there are multiple
columns of information and that the list is not alphabetically sorted.
5.
6. cat name.list

7. Use the sort command to perform a basic sort of the list:


8.
9. sort name.list

10. Do the same sort, but send the output to a file. Then use the cat utility to view the file:
11.

Parimal Sudas Page 38


12. sort name.list > sorted.list ; cat sorted.list

13. Sort the list by first names. This requires skipping over the first field, which is the last name:
14.
15. sort +1 name.list

16. Sort the list by department. This requires skipping over the first four fields and using the -b
option to ignore blank characters:
17.
18. sort -b +4 name.list

19. Return to the tutorial to learn about the next section before proceeding.

pwd

1. Read/scan the man page for pwd with the command:


2.
3. man pwd

4. Issue the pwd command to display the name of your current working directory:
5.
6. pwd

7. Change to several other directories and issue the pwd command between each change. Notice
the different outputs:
8.
9. cd dir4
10. pwd
11. cd /usr/bin
12. pwd
13. cd /var/spool
14. pwd
15. cd ~/Filesystem
16. pwd

mkdir

1. Read/scan the man page for mkdir with the command:


2.
3. man mkdir

Parimal Sudas Page 39


4. First make sure that you are in your Filesystem directory. Then, create a new directory with the
mkdir command. List your directory after the command completes to prove that it worked:
5.
6. cd ~/Filesystem
7. mkdir newdir
8. ls

9. Now create some additional subdirectories within your newdir. List newdir after the command
completes to prove that it worked:
10.
11. mkdir newdir/sub1 newdir/sub2 newdir/sub3
12. ls newdir

13. Try to create a directory in a location where you don't have permission. What happens?
14.
15. mkdir /etc/mydir

cd

1. Read/scan the man page for cd with the command:


2.
3. man cd

4. Change to your default, home directory:


5.
6. cd

7. Change to a subdirectory within you home directory and list its contents:
8.
9. cd Filesystem/dir4/subdir1
10. ls

11. Go up one level to the current directory's parent directory and list the contents:
12.
13. cd ..
14. ls

15. Change to the root (top-most) directory and list the contents:
16.
17. cd /
18. ls

19. Change to another student's directory and list the contents:

Parimal Sudas Page 40


20.
21. cd ~studnt01
22. ls

23. Change to another one of your subdirectories and list the contents:
24.
25. cd ~/Filesystem/newdir
26. ls

27. Finally, change back to the exercise directory:


28.
29. cd ~/Filesystem

rmdir

1. Read/scan the man page for rmdir with the command:


2.
3. man rmdir

4. First make sure you are in the Filesystem directory. Then try to remove the newdir directory.
What happens?
5.
6. cd ~/Filesystem
7. rmdir newdir

8. Recursively list the contents of newdir. Notice that its subdirectories are all empty. Remove all
of the empty subdirectories within newdir and then list newdir again to confirm that they were
removed:
9.
10. ls -R newdir
11. rmdir newdir/*
12. ls -R newdir

13. Finally, remove the empty newdir directory:


14.
15. rmdir newdir

16. Return to the tutorial to learn about the next section before proceeding.

Parimal Sudas Page 41


Introduction to UNIX
Access Permissions Exercises
These exercises will familiarize you with the basic UNIX commands for working with file access
permissions.

1. Make sure that you are in your Filesystem exercise directory, and then do a long listing of your
files:
2.
3. cd ~/Filesystem
4. ls -al

5. Notice the access permissions assigned to each file. Can you tell:
o which files are directories?
o if a file is executable?
o who has write access to each file?
o who has read access to each file?
o who owns the file?
o which group the owner belongs to?
o which permissions the group has?
o which permissions others have?
6. Use the chmod command to change the permissions for some files. List the file before and after
each change and determine how the command changes the file permissions.
7.
8. ls -l names1
9. chmod o-r names1
10. ls -l names1
11.
12. ls -l names2
13. chmod g+w names2
14. ls -l names2
15.
16. ls -l file*
17. chmod go-r file*
18. ls -l file*

19. Try a chmod command with numerical access specifications:


20.
21. ls -l prog1
22. chmod 754 prog1
23. ls -l prog1

24. Look in your ~/.cshrc file and find where your umask setting is specified. What is it and what
does it do? How would you change it so that nobody except you could see your files?

Parimal Sudas Page 42


25.
26. cd
27. more .cshrc

28. Return to the tutorial to learn about the next section before proceeding.

Introduction to UNIX
Standard UNIX File System Exercises
These exercises will familiarize you with the overall organization of your UNIX filesystem.

1. Change directory to the root level and then list the contents.
2.
3. cd /
4. ls

How many files do you see which are mentioned in the tutorial as being common/standard UNIX
files?

5. Change to the /usr directory and list it, again noting how many files you see which are
mentioned in the tutorial as being common/standard UNIX files?
6.
7. cd /usr
8. ls

9. Spend some time navigating about the upper levels of the filesystem.... see how lost you can
get!! Try some of the other directories mentioned in the tutorial.

Don't forget that you can always use the pwd command to tell you where you are, and the
cd command to return to your home directory.

Unix Editors
• What is a text editor?
o A text editor is a program which enables you to create and manipulate character
data (text) in a computer file.
o A text editor is not a word processor although some text editors do include word
processing facilities.

Parimal Sudas Page 43


o Text editors often require "memorizing" commands in order to perform editing
tasks. The more you use them, the easier it becomes. There is a "learning curve"
in most cases though.
• There are several standard text editors available on most UNIX systems:
o ed - standard line editor
o ex - extended line editor
o vi - a visual editor; full screen; uses ed/ex line-mode commands for global file
editing
o sed - stream editor for batch processing of files
• In addition to these, other local "favorites" may be available:
o emacs - a full screen editor and much more
o pico - an easy "beginner's" editor
o lots of others

The Standard Display Editor - vi


• vi supplies commands for:
o inserting and deleting text
o replacing text
o moving around the file
o finding and substituting strings
o cutting and pasting text
o reading and writing to other files
• vi uses a "buffer"
o While using vi to edit an existing file, you are actually working on a copy of the
file that is held in a temporary buffer in your computer's memory.
o If you invoked vi with a new filename, (or no file name) the contents of the file
only exist in this buffer.
o Saving a file writes the contents of this buffer to a disk file, replacing its contents.
You can write the buffer to a new file or to some other file.
o You can also decide not to write the contents of the buffer, and leave your original
file unchanged.
• vi operates in two different "modes":
o Command mode
 vi starts up in this mode
 Whatever you type is interpreted as a command - not text to be inserted
into the file.
 The mode you need to be in if you want to "move around" the file.
o Insert mode
 This is the mode you use to type (insert) text.
 There are several commands that you can use to enter this mode.
 Once in this mode, whatever you type is interpreted as text to be included
in the file. You can not "move around" the file in this mode.

Parimal Sudas Page 44


 Must press the ESC (escape) key to exit this mode and return to command
mode.

vi Commands
• Entering vi

• vi filename - The filename can be the name of an
• existing file or the name of the file
• you want to create.
• view filename - Starts vi in "read only" mode. Allows
• you to look at a file without the risk
• of altering its contents.

• Exiting vi

• :q - quit - if you have made any changes, vi
• will warn you of this, and you'll need
• to use one of the other quits.
• :w - write edit buffer to disk
• :w filename - write edit buffer to disk as filename
• :wq - write edit buffer to disk and quit
• ZZ - write edit buffer to disk and quit
• :q! - quit without writing edit buffer to disk

• Positioning within text



• By character
• left arrow - left one character
• right arrow - right one character
• backspace - left one character
• space - right one character
• h - left one character
• l - right one character

• By word
• w - beginning of next word
• nw - beginning of nth next word
• b - back to previous word
• nb - back to nth previous word
• e - end of next word
• ne - end of nth next word

• By line

Parimal Sudas Page 45


• down arrow - down one line
• up arrow - up one line
• j - down one line
• k - up one line
• + - beginning of next line down
• - - beginning of previous line up
• 0 - first column of current line (zero)
• ^ - first character of current line
• $ - last character of current line

• By block
• ( - beginning of sentence
• ) - end of sentence
• { - beginning of paragraph
• } - end of paragraph

• By screen
• CTRL-f - forward 1 screen
• CTRL-b - backward 1 screen
• CTRL-d - down 1/2 screen
• CTRL-u - up 1/2 screen
• H - top line on screen
• M - mid-screen
• L - last line on screen

• Within file
• nG - line n within file
• 1G - first line in file
• G - last line in file

• Inserting text

• a - append text after cursor *
• A - append text at end of line *
• i - insert text before cursor *
• I - insert text at beginning of line *
• o - open a blank line after the current
• line for text input *
• O - open a blank line before the current
• line for text input *

• * Note: hit ESC (escape) key when finished inserting!

Parimal Sudas Page 46


• Deleting text

• x - delete character at cursor
• dh - delete character before cursor
• nx - delete n characters at cursor
• dw - delete next word
• db - delete previous word
• dnw - delete n words from cursor
• dnb - delete n words before cursor
• d0 - delete to beginning of line
• d$ - delete to end of line
• D - delete to end of line
• dd - delete current line
• d( - delete to beginning of sentence
• d) - delete to end of sentence
• d{ - delete to beginning of paragraph
• d} - delete to end of paragraph
• ndd - delete n lines (start at current line)

• Changing text

• cw - replace word with text *
• cc - replace line with text *
• c0 - change to beginning of line *
• c$ - change to end of line *
• C - change to end of line *
• c( - change to beginning of sentence *
• c) - change to end of sentence *
• c{ - change to beginning of paragraph *
• c} - change to end of paragraph *
• r - overtype only 1 character
• R - overtype text until ESC is hit *
• J - join two lines

• * Note: hit ESC (escape) key when finished changing!

• Copying lines

• yy - "yank": copy 1 line into buffer
• nyy - "yank": copy n lines into buffer

Parimal Sudas Page 47


• p - put contents of buffer after current
• line
• P - put contents of buffer before current
• line

• Moving lines (cutting and pasting)



• ndd - delete n lines (placed in buffer)
• p - put contents of buffer after current
• line
• P - put contents of buffer before current
• line

• Searching / Substituting

• /str - search forward for str
• ?str - search backward for str
• n - find next occurrence of current string
• N - repeat previous search in reverse
• direction

• The substitution command requires a line range
• specification. If it is omitted, the default
• is the current line only. The examples below
• show how to specify line ranges.

• :s/old/new - substitute new for first occurrence
• of old in current line
• :s/old/new/g - substitute new for all occurrences
• of old in current line
• :1,10s/old/new - substitute new for first occurrence
• of old in lines 1 - 10
• :.,$s/old/new - substitute new for first occurrence
• of old in remainder of file
• :.,+5s/old/new - substitute new for first occurrence
• of old in current line and next 5 lines
• :.,-5s/old/new - substitute new for first occurrence
• of old in current line and previous
• 5 lines
• :%s/old/new/g - substitute new for all occurrences
• of old in the entire file
• :%s/old/new/gc - interactively substitute new for all
• occurrences of old - will prompt for
• y/n response for each substitution.

• Miscellaneous commands
Parimal Sudas Page 48

• u - undo the last command (including undo)
• . - repeat last command
• xp - swap two adjacent characters
• m[a-z] - set a marker (a - z)
• '[a-z] - go to a previously set marker (a - z)
• :!command - execute specified UNIX command
• :r filename - read/insert contents of filename after
• current line.
• :1,100!fmt - reformat the first 100 lines
• :!fmt - reformat the entire file

vi Options
• You can change the way vi operates by changing the value of certain options which
control specific parts of the vi environment.
• To set an option during a vi session, use one of the commands below as required by the
option:

• :set option_name
• :set option_name=value

• Some examples of the more common options are described below.



• :set all - shows all vi options in effect

• :set ai - set autoindent - automatically indents
• each line of text

• :set noai - turn autoindent off

• :set nu - set line numbering on

• :set nonu - turn line numbering off

• :set scroll=n - sets number of lines to be scrolled
• to n. Used by screen scroll commands.

• :set sw=n - set shiftwidth to n. Used by autoindent
• option.

• :set wm=n - set wrapmargin to n. Specifies number
• of spaces to leave on right edge of the
• screen before wrapping words to next
• line.

Parimal Sudas Page 49


• :set showmode - reminds you when you are inserting
• text.

• :set ic - ignore case of characters when
• performing a search.

• Options can be set permanently by putting them in a file called .exrc in your home
directory. A sample .exrc file appears below. Note that you do not need the colon (:) as
part of the option specification when you put the commands in a .exrc file. Also note that
you can put them all on one line.

• set nu ai wm=5 showmode ic

pico: One Alternative to vi


• pico is a simple text editor based upon the Pine Message/mail System. It is far easier to
use than vi, with the tradeoff that is isn't as powerful.
• Editing commands are entered using control-key combinations. The most important
commands are displayed at the bottom of the screen, facilitating ease of use.
• To start pico, simply use the command "pico" followed by the name of the file you wish
to edit. If the file exists, pico will start with that file. If it does not exist, then pico will
assume that it is a new file. An example pico startup screen is available here.
• The basic commands provided by pico include:

• CTRL-G - get help
• CTRL-X - exit
• CTRL-O - write out to a file
• CTRL-J - justify text
• CTRL-R - read a file
• CTRL-W - where is (search)
• CTRL-Y - previous page
• CTRL-V - next page
• CTRL-^ - mark cursor position as start of selected text
• CTRL-K - cut text
• CTRL-U - uncut text / paste
• CTRL-T - check spelling
• CTRL-C - cursor position information
• CTRL-F - move forward a character
• CTRL-B - move backward a character
• CTRL-P - move to the previous line
• CTRL-N - move to the next line
• CTRL-A - move to the beginning of the current line
• CTRL-E - move to the end of the current line
• CTRL-L - refresh the display

Parimal Sudas Page 50


• CTRL-D - delete the character at the cursor position
• CTRL-I - insert a tab at the current cursor position

• Note that cursor positioning can also be accomplished by
• using the up, down, right and left arrow keys.

• A few additional comments/notes:


o The manner in which lines longer than the display width are dealt is not
immediately obvious. Lines that continue beyond the edge of the display are
indicated by a '$' character at the end of the line. Long lines are scrolled
horizontally as the cursor moves through them.
o Context sensitive help is a feature included with pico.
o A file browser is included as part of the "write" and "read" file commands.

Introduction to UNIX
Editor Exercises
These exercises will familiarize you with the vi and pico editors.

Starting a vi Session

1. Open a new window or use an existing window for this exercise. Change directory to where the
editor exercises are located and list the files:
2.
3. cd ~/Editors
4. ls

5. Begin a vi session using the practice.1 file:


6.
7. vi practice.1

8. When the file appears on your screen, you will note several things:
o the file name and size appear at the bottom of the screen
o the cursor is in the top left corner of the screen
o one screen full of text appears, beginning with the first line in the file
o there are numerous mistakes and errors in the text...we'll deal with fixing these later.

IMPORTANT: The vi editor will always start in the command mode - whatever you type
will be interpreted as commands, not as text to be inserted.

Parimal Sudas Page 51


Cursor Positioning

1. Knowing how to position the cursor is important, since many vi commands use the cursor as the
reference point on where to execute the command.
2. Practice moving the cursor one character at a time:
3.
4. left arrow - left one character
5. right arrow - right one character
6. backspace - left one character
7. space - right one character
8. h - left one character
9. l - right one character

10. Practice moving the cursor word by word:


11.
12. w - beginning of next word
13. nw - beginning of nth next word
14. b - back to previous word
15. nb - back to nth previous word
16. e - end of next word
17. ne - end of nth next word

18. Practice moving the cursor line by line:


19.
20. down arrow - down one line
21. up arrow - up one line
22. j - down one line
23. k - up one line
24. + - beginning of next line down
25. - - beginning of previous line up
26. 0 - first column of current line (zero)
27. ^ - first character of current line
28. $ - last character of current line

29. Practice moving the cursor by block:


30.
31. ( - beginning of sentence
32. ) - end of sentence
33. { - beginning of paragraph
34. } - end of paragraph

35. Practice moving the cursor by screen:


36.
37. CTRL-f - forward 1 screen
38. CTRL-b - backward 1 screen
39. CTRL-d - down 1/2 screen
40. CTRL-u - up 1/2 screen
41. H - top line on screen
42. M - mid-screen

Parimal Sudas Page 52


43. L - last line on screen

44. Practice moving to specific lines within the file:


45.
46. nG - line n within file
47. 1G - first line in file
48. G - last line in file

49. Return to the tutorial to learn about the next section before proceeding.

Inserting Text

1. The "other" vi mode is the insert mode. In this mode, your typing will be interpreted as text to
be added to the document.
2. Assuming that you are still editing the ~/Editors/practice.1 file, put your cursor at the beginning
of the file (1G). Then place it on the first letter of the word: PEOPLE
3. Use the i command to put yourself in the insert mode. Now whatever you type will be text
added to the file. Type the word THE. Press the Esc key when you are finished to leave the insert
mode. The title should now say "THE PEOPLE OF HAWAII".
4. Now move your cursor to the last line of the first paragraph. This sentence obviously needs
completed. Use the o command to open a new line under the current line. This will put you into
the insert mode. Type the new line: Mainland U.S., and 15% are foreign-born. Press the Esc key
when you are finished to leave the insert mode.
5. The second line in the second paragraph is missing a word at the end of the line. Move your
cursor to this line. Then use the A command to append the word lowest at the end of the line.
Press the Esc key when you are finished to leave the insert mode.
6. The next line is also missing a word. Move your cursor to the end of the word permanent. Then
use the a command to append the word residents. Press the Esc key when you are finished to
leave the insert mode.
7. Save your editing changes to disk by typing the command :w Note that it is a good idea to save
your editing changes to disk frequently. This will help avoid losing work should your system
crash, or you accidentally kill your vi session.
8. Return to the tutorial to learn about the next section before proceeding.

Deleting Text

1. Assuming that you are still editing the ~/Editors/practice.1 file, note that the last word in the
second paragraph is spelled incorrectly. Move your cursor to the word livving. Place the cursor
directly on one of the v characters. Type x to delete it.
2. The first sentence of the third paragraph is exaggerating things a bit. Move your cursor to the
beginning of the word billion. Type the command 2dw to delete the two words billion trillion

Parimal Sudas Page 53


3. The next sentence also needs correction. Place your cursor directly after the comma which
follows the word Oahu. Delete the remainder of the line with the command D and pray that it
doesn't sink.
4. Now move your cursor down a couple lines to the point where a line has accidentally been
reproduce three times. Use the dd command to delete one of the excess lines. Then use it again
to delete the other excess line.
5. Move your cursor to the last paragraph. You'll notice that there are six blank lines under the first
sentence, which begins "With 100,000 people or so...". Place your cursor on the first blank line
and then remove all six blank lines with the command 6dd.
6. Ooops. There were only 5 blank lines! No problem. Use the u command to "undo" the previous
command. Now use the command 5dd to delete the five blank lines. The u command will come
in handy in future vi sessions, undoubtedly.
7. Save your editing changes to disk by typing the command :w
8. Return to the tutorial to learn about the next section before proceeding.

Changing Text

1. Assuming that you are still editing the ~/Editors/practice.1 file, return your cursor to the
beginning of the second paragraph. In the second line, you'll see the words changed wildly.
Place your cursor on the first character of the word changed. Use the cw command to change
this word to the word fluctuated.

Notice the dollar sign which appears. This shows you the end of the word which is being
changed. Notice also, that changing text puts you into the insert mode. You must press
the Esc key to exit the insert mode when you are finished with your change.

2. Now move your cursor down four more lines and find the words radically segregated. Put your
cursor on the first character of the word "radically". Then use the command 2cw to change
these two words to racially integrated. Press the Esc key to exit the insert mode when you are
finished with your change.
3. In the next line, the number 800,000 should be changed to 400,000. Put the cursor on the
number 8. Type r followed by the number 4. This command only replaces a single character, so
there is no need to press the Esc key.
4. The next line has another number which needs corrected. Put your cursor at the beginning of
the number 594,342. Type the R command followed by 500,000. You must press the Esc key to
exit the insert mode when you are finished with your change.
5. Move your cursor to the first line of the third paragraph. It can be joined with the short line
beneath it. Join this line to its following line with the J command. You should now have a single
line which reads, "Of the one million people in the islands today, 800,000 live on Oahu,".
6. When you are finished with the above changes, save the file and exit this vi session by typing the
command :wq or the command ZZ
7. If desired, you can compare your practice.1 file to the practice.1.final file. They should be very
close if not identical.
8. Return to the tutorial to learn about the next section before proceeding.

Parimal Sudas Page 54


Copying Lines

1. Assuming that you are still in your ~/Editors directory. Begin this exercise by editing the
practice.2 file with the command vi practice.2
2. Notice the three lines near the top of the document which look something like this:
3. ***********************************************************************
****
4. Chapter 1
5. ***********************************************************************
****

6. Copy these lines by moving your cursor to the first of the three and typing the command 3yy.
This will "yank" them into the copy buffer. Notice that the lines do not disappear...they are
copied.
7. Now move your cursor to the blank line which separates the first paragraph from the second
paragraph. Put the copied lines under this line by typing the p command.
8. Since you haven't performed any new editing commands which would overwrite the copy buffer
(such as a delete or another yank), the buffer contents are still intact. Now move your cursor to
the first line of the third paragraph.
9. Put the copied lines above this line by typing the P command.
10. Change the headings on the second and third paragraphs to indicate "Chapter 2" and "Chapter
3" accordingly. Use whatever "change text" editor command you wish for this.
11. Save your editing changes to disk by typing the command :w

Moving Lines (cutting and pasting)

1. Assuming that you are still editing the ~/Editors/practice.2 file, swap the first paragraph with
the second paragraph by following the steps below.
2. Place your cursor on the first non-heading line of the first paragraph - it begins, "A Hawaiian
tsunami is actually...". There should be seven lines in this paragraph. "Cut" these lines by using
the command 7dd. They will be placed in the copy/cut buffer.
3. Now, move your cursor to the first non-heading line of the second paragraph - it begins,
"Tsunami is the Japanese word for....". "Paste" the lines you just "cut" above this line by using
the P command.
4. Move the cursor down to what used to be the first line of the second paragraph - it begins,
"Tsunami is the Japanese word for ..."
5. "Cut" these five lines with the 5dd command. Note that these lines will be saved in the copy/cut
buffer, overlaying anything else which was there.
6. Move your cursor to the third "heading" line at the top of the document. It should be on a row
of asterisks.
7. "Paste" the new first paragraph under these asterisks by typing the p command.
8. When you are finished with the above changes, save the file and exit this vi session by typing the
command :wq or the command ZZ
9. If desired, you can compare your practice.2 file to the practice.2.final file. They should be very
close if not identical.

Parimal Sudas Page 55


10. Return to the tutorial to learn about the next section before proceeding.

Searching / Substituting

1. Assuming that you are still in your ~/Editors directory, begin this exercise by editing the file
practice.3. This file is somewhat larger than the previous two files. In real editing jobs, files can
be very sizeable. Being able to search quickly through a large document is an important time
saver. Knowing how to make global changes can also save lots of time.
2. You discovered that somewhere in your document the word "lingers" has been spelled
incorrectly as "ligers". Find the incorrect word by using the command /ligers and then correct it.
3. You also discovered another typo. Find the misspelled word "famly" with the command /famly
and change it to "family".
4. Return to the first paragraph near the top of the document. Place your cursor at the beginning
of the first line. Notice the grammatical mistake in this sentence - the word "natives" should be
"native". Make the change using the substitution command:
5.
6. :s/natives/native/

7. The word "kahuna" has been misspelled as "kahuuna" in a number of places. Rather than finding
and changing every occurrence individually, do a global substitution with the command
8.
9. :%s/kahuuna/kahuna/gc

Note that the gc option is used, which cause you to be prompted for each change. Enter either a
"y" or "n" for "yes" or "no". Omitting the c will cause the substitutions to occur without
prompting.

10. Find and remove all of the lines which look something like:

Return to Table of Contents.

You could do a global substitution, however, it would fail if any occurrence had extra spaces,
was missing the period, or was even slightly different in any way.

One method for making sure they are all changed is described below:

1.
Return your cursor to the top of the document
2.
Search for the first occurrence with the command /Return
3.
When it is found, delete it with the dd command
4.
Find the next occurrence with the n command
5.
Delete it as before and repeat the n and dd commands until all occurrences have been
removed.
11. When you are finished with the above changes, save the file and exit this vi session by typing the
command :wq or the command ZZ
Parimal Sudas Page 56
12. If desired, you can compare your practice.3 file to the practice.3.final file. They should be very
close if not identical.
13. Return to the tutorial to learn about the next section before proceeding.

Miscellaneous Commands
Assuming that you are still in your ~/Editors directory, begin this vi editing session with the practice.3
file.

1. Setting Markers
2. The use of markers can save time by allowing you to jump back and forth quickly
between different parts of the document.
3. Put your cursor at the beginning of the file. Use the search command /Polynesian Roots
to find the beginning of Polynesian Roots section. You will probably encounter the first
occurrence in the outline. Ignore this one and repeat the search by just typing /
4. Set marker "a" here by using the command ma
5. Now use the search command /Fatal Flaws to find the beginning of that section.
6. Set marker "b" here by using the command mb
7. Practice jumping back and forth between marker a and marker b with the commands 'a
and 'b
8. Let your imagination roam on just how useful 26 markers (a-z) can be. If you ever use
more than five, you'll either make the Guiness Book or create a file nobody can figure
out.
9. Reading and Writing Other Files
10. Go to the beginning of the practice.3 file. Add an item #8 to the Table of Contents. Call it
"Madame Pele". What? You want the commands on how to do this? We already learned
that. OK, here they are:
11.
12. 1G
13. /7
14. o
15. 8. Madame Pele
16. Esc the escape key - don't type "Esc"

17. Now go to the end of the document and place your cursor on the very last line. Then,
use the command :r pele.txt to read in a file which contains a story about the goddess
Pele. Read the story if you wish - Pele would insist. A volcano will erupt if you don't.
18. Save your modified practice.3 file as a new and different file with the command
19.
20. :w new.practice.3

Note that this will not change the fact that you are still editing the file practice.3.
This means you can create virtually any file you wish from within a vi session.

21. Issuing UNIX Commands From Within vi

Parimal Sudas Page 57


22. Assuming that you are still editing practice.3, prove that the file new.practice.3 was
created in the previous step by issuing this command from within your vi session:
23.
24. :! ls -l

25. You should see a long listing of your working directory which includes the
new.practice.3 file. Notice that vi will prompt you to hit the return key to resume
editing.
26. Other UNIX commands can be executed from within a vi session similarly.
27. Exit this session without saving any changes by using the command :q!
28. !fmt
29. Assuming that you are still in your ~/Editors directory, begin an editing session with the
file kam.txt. After it appears, you'll notice that the lines are formatted rather poorly.
30. Use the command below to reformat the entire file. The dollar sign is simply a
shorthand which means "to the end of the file".
31.
32. :1,$ !fmt

This command can also be used to reformat a range of lines. For example, the command
below would reformat lines 1 - 100.

:1,100 !fmt

33. When you are finished with the above, save the file and exit this vi session by typing the
command :wq or the command ZZ
• Return to the tutorial to learn about the next section before proceeding.

vi Options

1. Assuming that you are still in your ~/Editors directory, edit the file vi.options. As you read it,
you'll notice that it explains several vi options, all of which are non-essential to the function of vi
- they simply set preferences.
2. Try the nu option by typing the command below. What happens?
3.
4. :set nu

5. Experiment with the ai option. You'll have to actually try adding lines of text to observe its
effects.
6. Experiment with the showmode option. You'll have to actually do some text insertions to see
what happens (the words INPUT MODE should appear in the lower right corner when you are in
input mode).
7. Toggle on/off between the options. For example:

Parimal Sudas Page 58


8.
9. :set nu
10. :set nonu

11. Exit this editing session without saving anything by using the command :q!
12. Return to the tutorial to learn about the next section before proceeding.

pico: One Alternative to vi

1. pico is so easy to use that you don't even need these instructions. So, they're going to be short.
2. Assuming that you are still in your ~/Editors directory, open a pico editor session with the file
maui.txt
3.
4. pico maui.txt

5. Move around the initial screen with the arrow keys. Then try to type something...notice that
there is no "insert mode" and "command mode" like vi. Your typing is automatically interpreted
as text to insert into the document.
6. Try deleting text, moving the cursor around and adding blank lines
7. Now try cutting/pasting text, reading another file into the current editing session and writing
the buffer out as a different file... and anything else you'd like.

To accomplish tasks, you'll need the correct control character sequences, all of which are
documented in the tutorial or at the bottom of your pico screen.

8. If you have problems, the context-sensitive "help" CTRL-G can be used for assitance.
9. When you are finished, CTRL-X can be used to exit and optionally save the editor buffer as a file.

What is the Shell


• Whenever you login to a Unix system you are placed in a program called the shell. All of
your work is done within the shell.
• The shell is your interface to the operating system. It acts as a command interpreter; it
takes each command and passes it to the operating system. It then displays the results of
this operation on your screen.
• There are several shells in widespread use. The most common ones are described below.

Bourne shell (sh)


Original Unix shell written by Steve Bourne of Bell Labs. Available on all UNIX
systems. Does not have the interactive facilites provided by modern shells such as the C
shell and Korn shell. The Bourne shell does provide an easy to use language with which
you can write shell scripts.
C shell (csh)

Parimal Sudas Page 59


Written at the University of California, Berkley. As it name indicates, it provides a C like
language with which to write shell scripts.
Korn shell (ksh)
Written by David Korn of bell labs. It is now provided as the standard shell on Unix
systems. Provides all the features of the C and TC shells together with a shell
programming language similar to that of the original Bourne shell.
TC Shell (tcsh)
Available in the public domain. It provides all the features of the C shell together with
EMACS style editing of the command line.
Bourne Again Shell (bash)
Public domain shell written by the Free Software Foundation under their GNU initiative.
Ultimately it is intended to be a full implementation of the IEEE Posix Shell and Tools
specification. Widely used within the academic commnity. Provides all the interactive
features of the C shell (csh) and the Korn shell (ksh). Its programming language is
compatible with the Bourne shell (sh).

• Your login shell is usually established by the local System Administrator when your
userid is created. You can determine your login shell with the command:

echo $SHELL

• Each shell has a default prompt. For the 5 most common shells:

• $ (dollar sign) - sh, ksh, bash
• % (percent sign) - csh, tcsh

• Depending upon the shell, certain features will be available. The table below summarizes
the features available with the 5 most common shells. Note: these features will be
described in detail later.

• Bourne C TC Korn BASH
• sh csh tcsh ksh bash
• ______________________________________________________
• Programming language Yes Yes Yes Yes Yes
• Shell variables Yes Yes Yes Yes Yes
• Command alias No Yes Yes Yes Yes
• Command history No Yes Yes Yes Yes
• Filename completion No Yes* Yes Yes* Yes
• Command line editing No No Yes Yes* Yes
• Job control No Yes Yes Yes Yes
• ______________________________________________________

• * not the default setting for this shell

Parimal Sudas Page 60


Processes
• Whenever you enter a command at the shell prompt, it invokes a program. While this
program is running it is called a process. Your login shell is also a process, created for
you upon logging in and existing until you logout.
• UNIX is a multi-tasking operating system. Any user can have multiple processes running
simultaneously, including multiple login sessions. As you do your work within the login
shell, each command creates at least one new process while it executes.
• Process id: every process in a UNIX system has a unique PID - process identifier.
• ps - displays information about processes. Note that the ps command differs between
different UNIX systems - see the local ps man page for details.

To see your current shell's processes:

% ps
PID TTY TIME CMD
26450 pts/9 0:00 ps
66801 pts/9 0:00 -csh

To see a detailed list of all of your processes on a machine (current shell and all other
shells):

% ps uc
USER PID %CPU %MEM SZ RSS TTY STAT STIME TIME COMMAND
jsmith 26451 0.0 0.0 120 232 pts/9 R 21:01:14 0:00 ps
jsmith 43520 0.0 1.0 300 660 pts/76 S 19:18:31 0:00 elm
jsmith 66801 0.0 1.0 348 640 pts/9 S 20:49:20 0:00 csh
jsmith 112453 0.0 0.0 340 432 pts/76 S Mar 03 0:00 csh

To see a detailed list of every process on a machine:

% ps ug
USER PID %CPU %MEM SZ RSS TTY STAT STIME TIME COMMAND
root 0 0.0 0.0 8 8 - S Feb 08 32:57 swapper
root 1 0.1 0.0 252 188 - S Feb 08 39:16
/etc/init
root 514 72.6 0.0 12 8 - R Feb 08 28984:05 kproc
root 771 0.2 0.0 16 16 - S Feb 08 65:14 kproc
root 1028 0.0 0.0 16 16 - S Feb 08 0:00 kproc
{ lines deleted }
root 60010 0.0 0.0 1296 536 - S Mar 07 0:00 -ncd19:0
kdr 60647 0.0 0.0 288 392 pts/87 S Mar 06 0:00 -ksh
manfield 60968 0.0 0.0 268 200 - S 10:12:52 0:00 mwm
kelly 61334 0.0 0.0 424 640 - S 08:18:10 0:00 twm

Parimal Sudas Page 61


sjw 61925 0.0 0.0 552 376 - S Mar 06 0:00 rlogin
kanaha
mkm 62357 0.0 0.0 460 240 - S Feb 08 0:00 xterm
ishley 62637 0.0 0.0 324 152 pts/106 S Mar 06 0:00 xedit
march2
tusciora 62998 0.0 0.0 340 448 - S Mar 06 0:05 xterm -e
dilfeath 63564 0.0 0.0 200 268 - S 07:32:45 0:00 xclock
tusciora 63878 0.0 0.0 548 412 - S Mar 06 0:41 twm

• kill - use the kill command to send a signal to a process. In most cases, this will be a kill
signal, hence the command name. However, other types of signals are usually supported.
Note that you can only kill processes which you own. The command syntax is:

kill [-signal] process_identifier(PID)

Examples:

kill 63878 - kills process 63878


kill -9 1225 - kills (kills!) process 1225. Use if
simple kill doesn't work.
kill -STOP 2339 - stops process 2339
kill -CONT 2339 - continues stopped process 2339
kill -l - list the supported kill signals

You can also use CTRL-C to kill the currently running process.

• Suspend a process: Use CTRL-Z.


• Background a process: Normally, commands operate in the foreground - you can not do
additional work until the command completes. Backgrounding a command allows you to
continue working at the shell prompt.

To start a job in the background, use an ampersand (&) when you invoke the command:

myprog &

To put an already running job in the background, first suspend it with CRTL-Z and then
use the "bg" command:

myprog - execute a process


CTRL-Z - suspend the process
bg - put suspended process in background

• Foreground a process: To move a background job to the foreground, find its "job"
number and then use the "fg" command. In this example, the jobs command shows that

Parimal Sudas Page 62


two processes are running in the background. The fg command is used to bring the
second job (%2) to the foreground.

• jobs
• [1] + Running xcalc
• [2] Running find / -name core -print
• fg %2

• Stop a job running in the background: Use the jobs command to find its job number, and
then use the stop command. You can then bring it to the foreground or restart execution
later.

• jobs
• [1] + Running xcalc
• [2] Running find / -name core -print
• stop %2

• Kill a job running in the background, use the jobs command to find its job number, and
then use the kill command. Note that you can also use the ps and kill commands to
accomplish the same task.

• jobs
• [1] + Running xcalc
• [2] Running find / -name core -print
• kill %2

• Some notes about background processes:


o If a background job tries to read from the terminal, it will automatically be
stopped by the shell. If this happens, you must put it in the foreground to supply
the input.
o The shell will warn you if you attempt to logout and jobs are still running in the
background. You can then use the jobs command to review the list of jobs and act
accordingly. Alternately, you can simply issue the logout command again and you
will be permitted to exit.

Redirection
• Redirection refers to changing the shell's normal method of handling standard output
(stdout), standard input (stdin) and standard error (stderr) for processes. By default, all of
these are from/to your screen.

Parimal Sudas Page 63


• The following symbols are used on the shell command line to redirect a process's stdin,
stdout and/or stderr to another location, such as a file or device.

• > - redirect stdout (overwrite)
• >> - redirect stdout (append)
• < - redirect stdin
• 2> - redirect stderr (sh,ksh,bash)
• >& - redirect stdout and stderr (csh,tcsh)

• Examples:

• mail tony < memo - uses the file memo as input
• to the mail program
• ls -l > my.directory - redirects output of ls -l
• command to a file called
• my.directory. If the file
• already exists, it is
• overwritten
• cat Mail/jsmith >> Oldmail - appends the contents of
• Mail/jsmith to the file
• Oldmail (does not overwrite)
• myprog >& output - redirects stdout and stderr
• from myprog's execution to
• a file called output
• (csh,tcsh)
• (myprog > out) >& err - redirects stdout from myprog's
• execution to a file called out
• and stderr to the file err
• (csh,tcsh)
• myprog 2> runtime.errors - redirects stderr from
• myprog's execution to a
• file called runtime.errors
• (sh,ksh,bash)
• myprog > output 2>& - redirects stderr and stdout
• from myprog's execution
• to a file called output
• (sh,ksh,bash)
• myprog > out 2> err - redirects stdout from myprog's
• execution to a file called out
• and stderr to the file err
• (sh,ksh,bash)

Parimal Sudas Page 64


Pipes
• A pipe is used by the shell to connect the stdout of one command directly to the stdin of
another command.
• The symbol for a pipe is the vertical bar ( | ). The command syntax is:

• command1 [arguments] | command2 [arguments]

• Pipes accomplish with one command what otherwise would take intermediate files and
multiple commands. For example, operation 1 and operation 2 are equivalent:

• Operation 1
• who > temp
• sort temp

• Operation 2
• who | sort

• Pipes do not affect the contents of the input files.


• Two very common uses of a pipe are with the "more" and "grep" utilities. Some
examples:

• ls -al | more
• who | more
• ps ug | grep myuserid
• who | grep kelly

Filters
• A filter is a command that processes an input stream of data to produce an output stream
of data.
• Command lines which use a filter will include a pipes to connect it to the stdout of one
process and the stdin of another process.
• For example, the command line below takes the output of "who" and sorts it. The sorted
output is then passed to the lp command for printing. In this example, sort is a filter.

• who | sort | lp

• Both filters and pipes demonstrate a basic UNIX principle: Expect the output of every
program to become the input of another, yet unknown, program to combine simple tools
to perform complex tasks.

Parimal Sudas Page 65


Features (csh)
Each shell has its own set of features. Those of the C Shell are discussed below.

• Command history: The history mechanism maintains a list of recently used command
lines, called events. Provides a shorthand for reexecuting previous commands. To use
history:
1. Set the history variable:
2.
3. set history = 100

4. Issue the history command and view the output:


5.
6. history
7.
8. 35 12:34 sort < unsorted > sorted.list
9. 36 12:34 cat sorted.list
10. 37 12:35 ls * > unsorted
11. 38 12:35 cat unsorted
12. 39 12:35 ls
13. 40 13:06 history
14. 41 13:08 alias
15. 42 13:11 ls
16. 43 13:11 vi .cshrc

17. To save history events across all login sessions, set the savehistory variable:
18.
19. set savehistory = 50

• Event reexecution: Allows you to specify a shorthand for reexecuting a previous event.
Works with the history list.

• !! - repeats last command
• !number - repeats numbered command from history list
• !string - repeats last command starting with string

• Modifying previous events: Allows you to correct typos in previous command, or modify
it to create a new command.

• ^old^new - changes the string "old" to the
• string "new" in the last command
• issued

Parimal Sudas Page 66


• !number:s/old/new/ - changes numbered command from
• history list; substitutes the
• string "old" with the string "new".
• Note that there is no space
• between number and :

• Aliases: The alias command allows you to define new commands. Useful for creating
shorthands for longer commands. The syntax is.

• alias entered_command executed_command

Some examples:

alias m more
alias rm "rm -i"
alias h "history -r | more"
alias xpvm /source/pd/xpvm/src/RS6K/xpvm

To view all current aliases:

alias

To remove a previously defined alias:

unalias alias_name

• Filename Generation: When you give the shell abbreviated filenames which contain
special characters (metacharacters), it can generate filenames which match existing files.
Some examples appear below:

• ls *.txt - list files with .txt suffix
• ls [abc]* - list files with names that start with a,
• b or c
• lpr prog?.c - print files named prog?.c where ? is
• any character
• cd ~jsmith - change to user jsmith's home directory

You can "turn off" filename generation by setting the noglob variable. This will permit
special characters to be interpreted literally. For example:

set noglob

Parimal Sudas Page 67


• Filename Completion: The shell will complete a filename for you if you type in only
enough characters to make the name unique. This feature is a great time saver and helps
to prevent typos when trying to type long filenames.

To use filename completion, you need to set filec, either on the command line or in one
of your initialization files.

set filec

Then, when specifying a filename, type the part which is unique and hit the escape key (C
shell) or tab key (TC Shell). For example, if you had a directory with a long name, such
as "Introduction.UNIX.Filesystems", you could cd to that directory by using the cd
command with only a portion of the file's name, provided that the portion you specify is
unique (no other files have similar names)

cd Intro<ESC>

Note: typing a portion of a filename and then hitting CTRL-D instead of ESCape or TAB
will display a list of the filenames which match.

Variables (csh)
Each shell has its own set of variables and rules for using variables. Those associated with the C
Shell are discussed below.

• The shell has variables which are predefined as well as variables which you define (user
defined).
• Shell variables control many aspects of how your shell environment behaves. Modifying
these variables (and creating new ones) allows you to customize your shell environment.
• Shell variables are used extensively when creating shell scripts (covered later).
• Variables can be
o local - current shell only
o global - current shell and child processes/shells
o string - treated as character
o numeric - treated as numbers
o arrays - contain more than one value
• Commands used to declare and manipulate shell variables:

• set - assigns non-numeric string variables
• locally
• unset - removes a previously "set" variable
• set - shows all "set" variables
• setenv - assigns non-numeric string variables
Parimal Sudas Page 68
• globally
• unsetenv - removes a previously setenv variable
• setenv - shows all setenv variables
• @ - assigns numeric variables locally
• echo $variable - displays value of variable

• Examples

• set name=fred - Sets variable name to
• value of fred
• unset name - Unsets the variable name
• set path=($path . ~/bin) - Adds to current setting
• of string array variable
• path
• setenv DISPLAY makena:0 - Sets environment variable
• DISPLAY
• echo $HOME - Displays value of variable
• HOME
• set colors=(red green blue) - Assigns three values to
• the string array variable
• colors
• @ count = 1 - Sets numeric variable
• count to one
• @ count = ($count + 1) - Adds one to numeric
• variable count
• set counts = (1 22 4 9) - Assigns 4 values to
• numeric array variable
• counts
• @ counts[2] = 5 - Assigns values to second
• element of numeric array
• variable counts
• @ echo $counts[3] - Displays value of third
• element of numeric array
• variable counts

• Predefined Shell Variables. A number of shell variables are predefined by the shell itself
or inherited from the system environment. Some of the more common ones are described
below.

$
Contains the process id of the current shell
argv
Contains the command line arguments for an invoked command. argv is an array, with
$argv[0] set to the name of the invoked command, $argv[1] set to the first argument,
$argv[2] set to the second argument...and so on. $argv[*] can be used to specify all
arguments. You may also use the shorthand $n where n is the number of the argument.

Parimal Sudas Page 69


#argv
Set to the actual number of arguments in argv, excluding argv[0]
cdpath
Expands the search path for the cd command. By default, the cd command issued with a
simple filename will search only the working directory. Use cdpath to increase the
number of directories searched.
set cdpath=(/usr/jenny /usr/jenny/mail ../)
CWD or cwd
Holds that name of the working/current directory.
echo
Causes the shell to echo the command before executing it. Use set/unset to turn this
on/off.
filec
Enables file completion. Use set/unset to turn this on/off.
history
Controls the size of the history list. 100 is recommended as safe size. If the number is too
large, the shell may run out of memory.
HOME or home
The pathname of your home directory
ignoreeof
Prevents exiting the shell by typing CTRL-D, and thus, prevents accidentally logging off.
Use set/unset to turn this on/off.
noclobber
Prevents you from accidentally overwriting a file when you redirect output. Use set/unset
to turn this on/off.
noglob
Prevents the shell from generating/expanding ambiguous filenames. Use set/unset to turn
this on/off.
notify
Tells the shell to notify you immediately when a background job completes. Ordinarily,
notification will wait until the next shell prompt to prevent interruption of work. Use set/
unset to turn this on/off.
PATH or path
Specifies the path that the shell searches when asked to execute a command. If an
executable is not found in the path, you must specify its full pathname.
prompt
Allows you to customize the shell prompt. By default, the C shell prompt is simply a
percent sign (%). For example, to display the machine name you are logged into as part
of your prompt:
set prompt = "`hostname -s`% "
savehist
Specifies how many the number of command events to save as history after you logout.
These events are saved in a file called .history in your home directory. The shell uses
these as your initial history after you login again.
shell
Contains the pathname of the shell

Parimal Sudas Page 70


status
Contains the exit status of the last executed command
USER or user
Contains you login userid
verbose
Causes the shell to display each command after a history substitution. Use set/unset to
turn this on/off.

Initialization Files
• System-wide shell initialization files are common on UNIX systems. These files can be
"sourced" automatically by the shell and are typically setup by the System Administrator
for the local environment.
• Some examples of system-wide initialization files might be:

• /etc/environment
• /etc/profile
• /etc/cshrc
• /etc/login

• Every shell provides a means for the user to customize certain aspects of the shell's
behavior. These customizations usually permit you to augment and/or override the
system-wide defaults.
• User customizations are specified in initialization files located in the top level of your
home directory.
• Naming: Depending upon the shell, you must name your initialization file(s) accordingly.

• Executed during interactive login
• .login - csh, tcsh
• .profile - sh, ksh, bash
• .bash_profile - bash (alternative 1)
• .bash_login - bash (alternative 2)

• Executed for every new shell
• .cshrc - csh, tcsh
• .tcshrc - tcsh
• .kshrc - ksh
• .bashrc - bash

• The C shell uses two files to set user preferences:


o .cshrc

Parimal Sudas Page 71


 runs at each login before the .login file
 runs whenever another shell is created
 runs when a new window is opened
 runs when many utilities are invoked
 typically sets alias information, path variable, filec, prompt, etc.
o .login
 runs at invocation of login shell, after the .cshrc file
 typically sets terminal characteristics and one time shell options and
environment variables
• After changing your .login or .cshrc files, you must "source" them for the changes to take
effect:

• source .login
• source .cshrc

• The system administrator may/may not provide you with default .cshrc and .login files
when you first obtain your userid. If they are provided, be careful about modifying them -
especially removing specifications which are required for your local system.
• Example .cshrc and .login files are provided below:
o .cshrc file
o .login file
• Continue the Shell Exercises

Logout Files
• You are able to specify commands which the shell will execute upon logout. These
commands are kept in a file located in the top level of your home directory.

• .logout> - csh, tcsh
• .bash_logout - bash

Introduction to UNIX
Shell Exercises
Determining Your Shell

1. Open a new window or use an existing window for this exercise. Then make sure that you are in
the Shell subdirectory:
2.

Parimal Sudas Page 72


3. cd ~/Shell

4. Observe your shell prompt - is it a $ or %? What does this tell you?


5. Find out which shell you are using with the command:
6.
7. echo $SHELL

8. Find out which shells are available on your system:


9.
10. which csh
11. which tcsh
12. which ksh
13. which bh
14. which bash

15. Try invoking other shells and notice how the prompt changes. Then list your processes to see
them
16.
17. sh
18. csh
19. ksh
20. bash
21. ps

22. Return to your original shell by exiting consecutively from each of the shells you started above.
List your processes to verify that you have only your original (tcsh) shell running:
23.
24. exit
25. exit
26. exit
27. exit
28. ps

29. Return to the tutorial to learn about the next section before proceeding.

Processes

1. Review the man page for the ps command


2.
3. man ps

4. Try using the ps command to list your processes. Then try to list other processes on the system.
For example:
5.

Parimal Sudas Page 73


6. ps
7. ps uc
8. ps ug
9. ps aux

10. Review the man page for the kill command


11.
12. man kill

13. Start a process which does nothing except sleep for 5000 seconds
14.
15. sleep 5000

Now try issuing some other commands, for example ls. What happens? Why won't the shell
accept any commands?

16. To kill a process which is running in the foreground, CTRL-C can usually be used. Kill the sleep
5000 process you just started in this manner. What happens after you kill the process? Try
another UNIX command, such as ls. Does it work now?
17. Start another sleep 5000 process, except this time, start it in the background:
18.
19. sleep 5000 &

Now try issuing some other commands, for example ls. What happens?

20. Use the jobs command to find out about jobs you have running in the background. What does
the output of the jobs command tell you?

Start a couple more sleep 5000 processes in the background and then use the jobs
command again. Do they all appear?

21. Bring the third sleep process into the foreground with the command fg %3 What happens? Can
you run anything else now? Why?
22. Suspend the foreground sleep process with the CTRL-Z command. What happens? Try the jobs
command now. What does it show?
23. A suspended process can be put in either the background or foreground. Use the bg %3
command to resume running the third sleep process in the background.
24. The kill command can be used in various ways. Kill the third sleep process with the command kill
%3 and then use the jobs command to check on it. What do you see?
25. Now use the ps command to view your processes. Do you see the remaining two sleep
processes? Notice their PIDs and then use the kill command to kill both of them. For example:
26. % ps
27. PID TTY TIME CMD
28. 15493 pts/0 0:00 sleep 1000
29. 18054 pts/0 0:00 sleep 1000

Parimal Sudas Page 74


30. 18309 pts/0 0:00 -tcsh
31. 27017 pts/0 0:00 ps
32. % kill 15493 18054
33. % ps
34. PID TTY TIME CMD
35. 15498 pts/0 0:00 ps
36. 18309 pts/0 0:00 -tcsh
37. [3] + Terminated sleep 1000
38. [2] + Terminated sleep 1000

39. Return to the tutorial to learn about the next section before proceeding.

Redirection

1. Redirect the output of the man command into a file instead of to your screen with the
command:
2.
3. man cp > cp.manpage

List your directory to confirm that the command worked. View the file with the more
cp.manpage command also.

4. Redirect the output of the ls -l command to a file and then view the file after the command
completes:
5.
6. ls -l ~/* > homedir.files

7. Redirect the input for mail by sending a file as the mail message. No interactive prompting will
be done by mail. Don't forget to substitute your userid and node number for the Xs below.
8.
9. mail studntXX@nodeX.class.mhpcc.edu < homedir.files

10. Redirect both the stdout and stderr from a command to a file. For example, type the command
ls * nosuchfile and notice that both the command output and an error message are displayed on
your screen. Then, type the command below to redirect both to a file. View the file after the
command completes.
11.
12. ls * nosuchfile >& ls.out-err

13. Redirection will overwrite existing files. To prove it, try the following sequence of commands:
14.
15. echo 'one' > file1
16. cat file1
17. echo 'two' > file1

Parimal Sudas Page 75


18. cat file1

19. You can append redirected output to an existing file if you use >> instead of >. Try to commands
below to prove it:
20.
21. echo 'one' > file1
22. cat file1
23. echo 'two' >> file1
24. cat file1

25. Redirection of both stdin and stdout can also be used. Assuming that you are still in your ~/Shell
directory, the following command will use the file unsorted as input to the sort utility and
produce a sorted file called sorted.list.
26.
27. sort < unsorted > sorted.list

28. Return to the tutorial to learn about the next section before proceeding.

Pipes and Filters

1. Obtain a sorted list of users on the system by piping the output of the who command to the
input of the sort command:
2.
3. who | sort

4. View all system processes one screen at a time by piping the output of the ps ug command to
the input of the more command:
5.
6. ps ug | more

7. View all studntXX processes one screen at a time by piping the output of the ps ug command to
the input of the grep command:
8.
9. ps ug | grep studnt

10. View all root processes one screen at a time by piping the output of three different commands
together. Note that in this example, the grep command is acting as a filter:
11.
12. ps ug | grep root | more

13. Return to the tutorial to learn about the next section before proceeding.

Parimal Sudas Page 76


Features (csh)

1. Command History: The student userids have already been setup to use the C Shell's command
history feature. To view your command history simply type the command history. What do you
see?
2. You may wish to view your command history in reverse chronological order (most recent
commands at beginning of list), one screen at a time:
3.
4. history -r | more

5. The student userids have been setup to use the Tcsh, which is an extended version of the C
Shell. It allows you to "cycle through" your command history by using the up arrow key. Try
pressing your up arrow key at the Shell prompt. Try it several times. Your previous commands
should appear, allowing you to edit them and/or press return to reexecute them.
6. Event Reexecution: Try reexecuting several events from your history list. An example is shown
below - note that your actual command history will differ:
7. % history -r more
8. 36 12:34 cat sorted.list
9. 35 12:34 sort < unsorted > sorted.list
10. 34 12:34 ls -l > unsorted
11. 33 12:32 sort < ls * > sorted.list
12. 32 12:23 ps ug | grep studnt
13. 31 12:22 ps ug | grep root | more
14. 30 12:20 ps ug | more
15. 29 12:18 ps aux
16. 28 12:16 ls
17. % !36

Now try reexecuting an event by using the !string method. For example, the command !his will
reexecute the last command you issued which began with the string "his" (such as a history
command).

Finally, try reexcuting a previous command by typing !!

18. Modifying Previous Events: First, type a command with an obvious typo:
19.
20. sort unsrted | grep Systems

After the shell tells you it can't open the file "unsrted", modify the command as shown below.
The command should now work.

^srt^sort

Parimal Sudas Page 77


Using the Tcsh, you could also accomplish this by recalling the command with the up arrow key
and then editing the command line.

21. Using Aliases: Create a few aliases and then use them:
22.
23. alias h "history -r | more"
24. h
25. alias ll "ls -l"
26. ll
27. alias rm "rm -i"
28. rm unsorted

Issue the alias command without any arguments. It should show you all of your defined aliases.

29. Filename Generation: You have been using this feature all along. For example:
30.
31. ls ~/Filesystem/*
32. ls ~/Filesystem/file*
33. ls ~/Filesystem/[ns]*

You can turn off filename generation with the command set noglob. Do this and then try the
same commands above. When you're convinced that it is turned off, turn it back on again with
the command unset noglob.

34. Filename Completion: Turn on this feature with the command set filec. Then, create a file with
a long name:
35.
36. touch Introduction.UNIX.Filesystems

Now, type the following and notice what happens. Note that you should use the actual Tab key
instead of the literal words "Tab key". Also note that some systems use the Esc key instead of
the Tab key.

ls IntTab key

37. Return to the tutorial to learn about the next section before proceeding.

Variables

1. Display your shell's variables with the set command. Review the list. Then, use the echo
command to display a few of them individually. For example:
2.

Parimal Sudas Page 78


3. echo $user
4. echo $home
5. echo $term

6. The PATH(path) variable is a very important variable. It determines the directory paths which
the shell will search when looking for an executable. Find out what your path is:
7.
8. echo $path
9. echo $path | fold - use this if it "runs off" the
10. right hand side of the screen

11. Display your shell's environment variables with the setenv command. Review the list. Then, use
the echo command to display a few of them individually. For example:
12.
13. echo $HOST
14. echo $MANPATH
15. echo $HOME

16. Try using variables with UNIX commands. For example:


17.
18. ls -l $HOME
19. echo My userid is $user and my machine is $HOST

20. Set a few variables of your own creation and then display/use them. For example:
21.
22. set myvar1 = "this is a string variable"
23. echo $myvar1
24.
25. setenv dir1 /usr/local/bin
26. ls $dir1
27.
28. set colors=(red green blue)
29. echo $colors[1]
30. echo $colors[2]
31. echo $colors[3]
32. echo $colors
33.
34. @ num1 = 256
35. @ num2 = 512
36. @ num3 = ($num1 + $num2)
37. echo $num3

38. Unset any of the variables you previously set and then try to display them. What happens? For
example:
39.
40. unset colors
41. echo $colors
42.

Parimal Sudas Page 79


43. unsetenv dir1
44. echo $dir1

45. Return to the tutorial to learn about the next section before proceeding.

Initialization Files

1. Change to your home directory and list all of your files including your hidden files. Which
initialization files mentioned in the tutorial do you see?
2.
3. cd
4. ls -a

5. Use either vi or pico to edit your .cshrc file. Notice the variables and aliases which have already
been set for you. Customize the file, perhaps creating some variables or aliases of your own. You
may get an idea or two from the example .cshrc file in the tutorial.
6. Use the command source .cshrc to effect the changes you made. Try them out...do they work?
7. View the system wide initialization file: /etc/environment. Note in particular how the PATH
variable is set. This is the default path for all users on the system.

Electronic Mail Overview


• Electronic mail, or email, provides a means for individuals and groups to electronically
correspond with each other across the global networks.
• Email can be used for more than sending correspondence. Data, images and even
computer programs can be sent within mail messages (file transfer). Email is also used as
the basis for other Internet services such as mailing lists and newsgroups.
• Every UNIX system allows you to exchange electronic mail with other users on your
local system. Most systems also allow you to exchange mail with users on remote
systems.
• Electronic mail is very quick. Messages will reach users on the same system almost
immediately; users on systems elsewhere in this country, or other countries, in a few
minutes, or hours at most.
• The standard UNIX mail utility which comes with most UNIX systems is called, simply
"mail". Another improved version, called "mailx" may also be available.
• There are a number of other, easier to use and more full featured electronic mail utilities
available for UNIX systems. In most cases, these do not come with the standard UNIX
operating system, but must be acquired and installed separately.
• Using email requires that you understand electronic mail addresses. In most cases, an
email address looks something like:

• username@somemachine.domain

Parimal Sudas Page 80


username
The userid of the addressee. This is usually a login name for the user on a computer that
is able to receive email. If the user is on the same computer as the mail sender, the rest of
the email address is not required.
@
The "at sign". Separates the username from the rest of the email address.
somemachine
The name of the computer where the addressee has a login name or userid.
domain
The Internet domain where somemachine is located. This portion of the address may
consist of one or more "words" separated by periods. Necessary for routing the email to
the correct destination.

• How do you find a person's email address?


o Ask them
o Check the "from" field on email which you have received. The from field usually
appears in the "header" portion of a mail message. For example:
o
o From: mbida@mail.mhpcc.edu
o Message-Id: <9502232348.AA127930@kanaha.mhpcc.edu>
o Subject: 400-way upgrade plan
o To: systems@mail.mhpcc.edu, services@mail.mhpcc.edu
o Date: Thu, 23 Feb 1995 13:48:50 -1000 (HST)

o May be able to use an Internet search tool such as "netfind" or "whois"


o UNIX "finger" utility
o Business cards, stationary

Standard UNIX Mail


• Mail allows you to
o compose a message and send it
o receive a message and display it
o save messages
o customize certain features
• When you are using the mail program you are in one of two "modes". Each mode has its
own set of commands.
o send mode - for creating and sending a mail message. Two character commands
which begin with a tilde (~) character.
o command mode - for reading and managing mail. Single character commands.

Parimal Sudas Page 81


Sending Mail
• Sending Mail - basic example
1. Enter the command:

mail username@address

2. You will then be prompted to enter the subject of your mail message. Enter the
subject title and press the Return key. If you make a mistake use the Backspace or
Delete key for corrections. For example:

Subject: Meeting tomorrow at 1:00

3. Enter the text of your message. Use the Backspace or Delete key for corrections.
Press the Return key whenever you want to start a new line. Note: you can not
back up to previous lines to make corrections. You will need to invoke an editor,
such as vi to accomplish this (covered later).
4. When you are finished typing the message, press the Return key to start a new
line and type CTRL-d. You will then be prompted for any addressees to Cc. You
may either enter additional email addresses or press the Return key if there is
nobody to copy. Your message will be sent and the shell prompt will be
displayed.

Send Mode Commands


• Send mode commands: allow you to perform various functions while you are in the
middle of composing your mail message.
• These commands are two characters, the first of which is the tilde (~) character.
• Must be issued as the first characters on a line in order to be interpreted as commands and
not message text.
• A list of the send mode commands appears below. Note that this set is not universal.
Different UNIX operating systems may have a different sets. The set below is for mail
running under IBM's AIX operating system.

Control Commands:
CTRL-D - Send message
~q - Quit editor without saving or sending
message
~p - Display the contents of the message buffer
~? - Display help
~:set - Show which mail options are in effect

Add to Heading:

Parimal Sudas Page 82


~h - Add to lists for To: Subject: Cc: and Bcc:
~t addrlist - Add user addresses in addrlist to the
To: list
~s subject - Set the Subject: line to the string
specified by Subject
~c addrlist - Add user addresses in addrlist to Cc: list
~b addrlist - Add user addresses in addrlist to Bcc: list

Add to Message:
~d - Append contents of dead.letter to message
~r filename - Append contents of filename to the message
~f numlist - Append contents of message numbers in
numlist
~m numlist - Append/indent contents of message numbers
in numlist

Change Message:
~e - Edit the message using an external
editor (default is e)
~v - Edit the message using an external
editor (default is vi)
~w filename - Write the message to filename
~! command - Start a shell, run command, and return
to the editor.
~| command - Pipe the message to standard input of
command; REPLACE the message with the
standard output from that command.

• Invoking an editor, with either the ~e or ~v command makes creating your message much
easier. If you use ~v, then the vi editor will be used. If you use ~e, you can use a different
editor, such as pico:

• ~:set EDITOR=/local/bin/pico - first specify the editor
• of choice
• ~e - then invoke it

• In addition to the ~r command, you can send a file in a mail message as shown below. In
this example, the file "asia.report" will be sent to the address jwwilliams@ibm.vnet.com.
No editing of the mail message is possible - it will be sent directly.

mail jwwilliams@ibm.vnet.com < asia.report

Reading Mail
• To read your mail, simply enter the command:

Parimal Sudas Page 83


mail

If you have any mail in your system mail box, an indexed list of the messages will be
displayed on your screen. For example:

> 1 pegwms@mhpcc.hpc.mil Wed Oct 26 14:49 94/3378 "Suggestions"


2 tfahey@mhpcc.hpc.mil Wed Feb 15 12:17 94/3308 "netfind"
3 lwaters@mhpcc.hpc.mil Wed Feb 15 16:27 29/916 "URL"
4 colek@mhpcc.hpc.mil Wed Feb 15 10:08 46/1784 "New Employees"
5 bob@soest.hawaii.edu Thu Feb 16 09:11 83/2868 "Images"
N 6 colek@mhpcc.hpc.mil Fri Feb 17 08:33 30/1166 "Fill Out Form"
N 7 tfahey@mhpcc.hpc.mil Fri Feb 17 09:01 48/1584 "Getting Started"
N 8 pegwms@mhpcc.hpc.mil Fri Feb 17 17:34 121/5011 "HPC Asia '95"
N 9 lijewski@HK.Super.NET Fri Feb 17 23:52 30/1229 "hi from HK"
&

In the above example, note that:

o > indicates the current message


o N indicates a new message
o Messages are numbered and sorted by date/time
o Message sender is displayed
o Message size in lines/characters appears
o Subject is displayed
o & is the mail prompt, telling you that you are in command mode and that mail is
ready to receive a command.
• To read the current message, just press the Return key
• To read a specific message other than the current message, type the message number.
This message will display and become the current message.
• To redisplay the message list, use the "h" command
• To display the next message, use the "n" command

Command Mode Commands


• Command mode commands: enable you to perform tasks related to reading and managing
your mail. These commands will always be entered at the "&" mail prompt. A summary
of the command mode commands for IBM AIX mail appears below:

Control Commands:
q - Quit - apply mailbox commands entered this
session
x - Quit - restore mailbox to original state
! cmd - Start a shell, run cmd, return to mailbox

Parimal Sudas Page 84


cd dir - Change directory to dir or $HOME
a - Display list of aliases with addresses
? - Display help
set - Show which mail options are in effect
folder filename - Make filename the current mail folder

- Display Commands:
Return key - Display current message
t - Display current message
t msg_list - Display messages in msg_list
n - Display next message
f msg_list - Display headings of messages in msg_list
h - Display headings or all messages

- Message Handling:
e num - Edit message num (default editor is e)
v num - Edit message num using vi editor
d msg_list - Delete messages in msg_list or current
message
u msg_list - Recall deleted messages
s msg_list file - Append messages (with headings) to file
w msg_list file - Append messages (text only) to file
pre msg_list - Keep messages in system mailbox

- Creating New Mail:


m addrlist - Create/send new message to addresses
in addrlist
r msg_list - Send reply to senders and recipients
of messages
R msg_list - Send reply only to senders of messages

Saving Mail and Using Folders


• One of the most useful features of mail is the ability to save mail messages and to
organize your mail the way you prefer.
• By default, mail will save all messages which you have read to a file in your home
directory called "mbox". You can choose to save messages to other files by using the "s"
command.
• Whenever you save a mail message, it is appended to the file you specify. Files can also
be called "folders", since they let you organize multiple mail messages into a common
location. Some examples of saving mail into folders appear below:

s jsmith - Save current message to file jsmith


in current directory
s 1-4 projects - Save messages 1 thru 4 to file
projects in current directory

Parimal Sudas Page 85


s 2 4 5 Mail/old/paul - Save messages 2,4,5 to file
Mail/old/paul

• By default, when you start mail, it uses your "system mailbox" as its folder. Your system
mailbox is usually located someplace like /usr/spool/mail or /var/spool/mail. It contains
new mail and previously unread mail.
• You can view other folders by starting mail with the -f option. For example, this
command will start mail with the folder "projects":

mail -f projects

• While you are in the mail program, you can switch between different folders by using the
"folder" command at the "&" prompt. For example, this command switchs the current
folder to "Mail/jsmith":

folder jsmith

• If you prefer to save all of your folders to a certain subdirectory, and don't wish to type
the full name of that directory everytime you save a message or switch folders, mail
provides a feature to make this more convenient.
o Set an environment variable called "folder" to point to the directory where all of
your mail folders should be kept. For example, the following line could be added
to your .cshrc file:

setenv folder Mail/folders

o When saving or accessing a folder, precede the folder name with a "plus sign" (+).
This will tell mail to use the location specified by your "folder" environment
variable. For example:
o
o s +projects
o
o mail -f +projects
o
o folder +projects

Customizing Your Mail Environment


• Mail has many options. The default option settings for your system are specified in a file
called:

/usr/lib/Mail.rc

Parimal Sudas Page 86


• Mail allows you to customize your mail environment and preferences. Your
customizations are specified in a file you create in your home directory, called ".mailrc".
These specifications will override or augment the system defaults.
• Some useful mail options are listed below.

Variable Action
-------- -----------------------------
alias name address - Creates an alias for a mail address
ask - Prompts for the subject of each message
sent
askcc - Prompts for carbon copy mail addresses
crt=lines - Defines the number of lines of a mail
message the Mail program displays before
pausing for input. Works with PAGER.
EDITOR=editor - Gives the full path name of the
editor to be started with the e mailbox
subcommand or the ~e mail editor
subcommand.
folder=directory - Directory to save mail files in.
hold - Keep messages that have been read in
the system mailbox, not the mbox file.
ignore fieldlist - Specifies which header fields to
not display(ignore)
keepsave - do not delete messages that have been
saved. Keep them in the system mailbox.
Use with the hold option.
nosave - Prevents retention of interrupted
letters in the $HOME/dead.letter file.
PAGER - the pager used to paginate output
when a message is longer than the
screen. Works with "crt" setting.
record=fileName - Defines a file in which to record
outgoing mail.
screen=lines - Defines the number of lines of
message headers displayed before pausing
for input.
topline=number - the number of lines of the top of each
message to print with the ~t command.
VISUAL=editor - the name of the editor called by
the ~v command. Editor is given as a
full pathname.

• A simple .mailrc file appears below. Note that more than one option can be placed on a
line.

• # Simple .mailrc file
• #
• set ask askcc EDITOR=/source/local/bin/pico folder=Mail
• set PAGER=more crt=20

Parimal Sudas Page 87


Pine: One Alternative to UNIX Mail
• Pine is a screen oriented, message handling (mail) tool.
• Pine is easy to use - your available commands are clearly visible at the bottom of each
screen.
• Pine's basic feature set includes:
o View, Save, Export, Delete, Print, Reply and Forward messages.
o Compose messages in a simple editor (pico) with word-wrap and a spelling
checker. Messages may be postponed for later completion.
o Full-screen selection and management of message folders.
o Address book to keep a list of long or frequently-used addresses. Personal
distribution lists may be defined. Addresses may be taken into the address book
from incoming mail without retyping them.
o New mail checking and notification occurs automatically every 2.5 minutes and
after certain commands, e.g. refresh-screen (Ctrl-L).
o On-line, context-sensitive help screens.
• To start pine at it's main menu, simply issue the command "pine". An example of pine's
main menu screen appears here.

Alternately, you can open pine directly into the email composer by using the command
"pine user@address". An example of pine's email composer screen appears here.

• System wide and personal configuration options can be used to tailor pine's behavior.
Your personal configuration options are specified in a file called ".pinerc" located in your
home directory.
• See the pine man page for additional details.

Introduction to UNIX
Electronic Mail Exercises
Sending Mail - Basic Example

1. Open a new window or use an existing window for this exercise. Then make sure that you are in
the Email subdirectory:
2.
3. cd ~/Email

4. Begin a mail message to yourself. You'll need to know your student userid and the name of your
classroom login machine. Your student userid is your login userid. To find your machine's name,
type the hostname command.

Parimal Sudas Page 88


Then begin the mail message by issuing the following command - being sure to substitute
your userid for "studntXX" and your machine name for "nodeX.class.mhpcc.edu".

mail studntXX@nodeX.class.mhpcc.edu

5. When prompted for the subject, make one up and then press the Return key.
6. You are now ready to type the actual mail message. Try typing several lines.
7. When you are ready to send the message, type CTRL-D. You will be prompted to Cc: someone,
but just hit the Return key to ignore it. Your mail is immediately sent.
8. Return to the tutorial to learn about the next section before proceeding.

Send Mode Commands

1. Start another mail message to yourself as before, being sure to substitute your userid for
"studntXX" and your machine name for "nodeX.class.mhpcc.edu"
2.
3. mail studntXX@nodeX.class.mhpcc.edu

Type in a subject and then a line or two of actual message.

4. Quitting a mail message: There will be times when you will not want to send the message after
you have started it. The ~q, typed as the very first two characters on a line will permit you to do
this. Use the ~q send mode command to quit this message.
5. Displaying help: Begin another mail message to yourself. Type in a subject and then a line or
two of actual message. Then use the ~? send mode command to display send mode help.
Remember that all send mode commands must be the first two characters on a line - otherwise,
they will just end up as part of the message text.
6. Displaying the message buffer: Type in a few more lines. Then use the ~p command to display
the progress of your message so far.
7. Changing the subject line: You may wish to change a message's subject line before you send it.
Type the following command to do this:
8.
9. ~s This is a New Subject

You may be confused and think this will become part of your mail message because it
appears to be in the message body. To prove that the command did what it was supposed
to do, use the ~p command to display the true contents of the mail message.

10. Reading in other files: Email is useful for more than just friendly correspondence. It is often
used for sending documents, data, images and even executable computer programs. These files
can be read into a mail message with the ~r command.

Parimal Sudas Page 89


Read the file add.me into your mail message by using the command below. Be sure to
use the ~p command to display the mail message afterwards.

~r add.me

11. Writing out to other files: You can always save a mail message you are in the middle of creating
by using the ~w command. This is useful if you have to leave and can't finish the mail message
right now. If you save it, you can pick up where you left off later by reading the file into a new
mail message. Try the command below, noting that a confirmational message will display after
the file is saved.
12.
13. ~w saved.message

14. Using other editors: Let's face it, the default mail editor is not useful for more than one line
messages. You will almost always want to invoke a different editor. Try one or both of the
following.
o Invoke the vi editor:
1. Type the ~v command. Your current mail message buffer will now appear via a
vi session.
2. Do some editing.
3. When you're ready to return to mail, use the :wq command. This will exit vi and
return you to mail's send mode.
4. Use the ~p command to confirm your vi editing changes.
o Invoke the pico editor:
1. This is slightly more complicated because you must first tell mail where this
alternate editor program is installed. It will vary on different systems. At the
prompt, type the command shown below.
2.
3. ~:set EDITOR=/source/local/bin/pico

4. Now, invoke the editor specified above: ~e


5. When pico appears, do some editing.
6. Use the CTRL-X command to exit. You will be asked to save the buffer - type "y".
Then the name of the temporary file where the editor is saving your work will
appear - just hit return to accept it. You will be returned to mail's send mode.
7. Use the ~p command to confirm your pico editing changes.

You will learn later how you can create a mail configuration file so that mail will know
where pico (or any other editor) is installed. Then you will not be required to use the
~:set command above.

15. Finish this mail file and send it to yourself by using the CTRL-D send mode command.

Parimal Sudas Page 90


16. Sending Files Directly: You can send a file directly, bypassing the usual interactive mail prompts.
Try the command below to send the "add.me" file to yourself. Don't forget to substitute your
own student userid and local machine name.
17.
18. mail studntXX@nodeX.class.mhpcc.edu < add.me

19. Return to the tutorial to learn about the next section before proceeding.

Reading Mail

1. Starting mail in command mode: By now, you have sent several messages to yourself. These
have been stored by the system. To read them, simply type the command mail. Your indexed list
of messages will appear.

Compare your indexed list against the tutorial's to understand the information which is
being displayed. In particular, notice the:

o pointer for the current message (>)


o message from field
o date/time field
o size field
o subject field.

The & prompt is your clue that you are in mail's command mode. You are not sending or
editing messages to others - you are "doing" your own mail.

2. Reading the current message: Read the current message by typing t or pressing the Return key.
What happens? When the message is completely displayed, the & prompt will indicate that mail
is ready to receive another command.

If the message is more than one screen in length, it will probably scroll off the screen
(this is system dependent). To prevent this, you can specify a "pager" program in the mail
configuration file - which will be covered later.

3. Reading the next message: You can read the next message simply by typing n or hitting the
Return key at the mail command prompt (&). Try both. If you get to the end of your messages,
mail will tell you At EOF , which means, "At End Of File".
4. Reading any message: You can read any message simply by typing its message number at the
mail command prompt (&). Read the first message again by typing the number 1 at the mail
command prompt (&). Try the same with another message number.
5. Return to the tutorial to learn about the next section before proceeding.

Parimal Sudas Page 91


Command Mode Commands

1. Getting help: Type the command ? to see the command mode help.
2. Displaying the message headings: The message heading list can be displayed by typing h at the
mail command prompt (&). This is useful to know if you forget which message is which. You can
also use the f command to display message headings for a range of messages. Try these
commands:
3.
4. h
5. f
6. f *
7. f 1-2

8. Deleting messages: Delete the first message in your mailbox with the command d1. Display your
message headings with the h command to confirm that it was deleted. Note that using the d
command without a message number will delete the current message. Also, the d command
accepts a list of messages or the wildcard character (*) as arguments.
9. Undeleting messages: Undelete the previously deleted message by using the u command.
Display your message headings with the h command to confirm that it was undeleted. Note that
the u command accepts a list of messages or the wildcard character (*) as arguments.
10. Replying to messages: The r and R commands are used for this...however, since the only mail
which you've received is from yourself, you'll have to try these with real mail later. Sorry.
11. Sending a new mail message: Use the command below to send another mail message to
yourself. This will put you into mail's send mode. Create a message and then send it off. You will
see it the next time you start up mail in command mode. Don't forget to substitute your userid
and machine name as appropriate.
12.
13. m studntXX@nodeX.class.mhpcc.edu

14. Issuing UNIX commands from within mail: To issue any UNIX command from within mail, simply
preceed that command name with an exclamation mark. Try the following:
15.
16. !ls
17. !ls -l
18. !date
19. !man cp

20. Quitting mail: You can exit mail with either the x or the q commands. If you choose x, then your
previous mail box commands (such as deletes) will not be retained and your mail will be saved
as though it was unread in the system mailbox.

If you choose q, then your mail box commands will be applied and your read messages
will be placed into a file called mbox in your home directory.

Quit mail by using the q command. Check your home directory for a file called mbox. It
contains your undeleted, read mail.
Parimal Sudas Page 92
21. Return to the tutorial to learn about the next section before proceeding.

Saving Mail and Using Folders

1. Understanding mbox: Mail will usually start by trying to read your system mailbox, located in a
"system" location, such as /usr/spool/mail/studntXX. This is where your new, unread mail is
kept.

Your previously read mail, however, will be kept in a file (folder) called mbox in your
home directory. Assuming that you have completed the previous exercises, you should
have several mail messages stored in the mbox folder.

Change directory to your home directory and make sure your mbox file exists:

cd
ls -l mbox

Assuming it does, start mail using your mbox folder:

mail -f mbox

2. Saving mail messages to a folder While you are in mail's command mode, you can use the s
command to save mail to another file/folder. For example, to save the current mail message to a
new file/folder, type the command:
3.
4. s new.folder

Try saving at least two or three messages to the folder new.folder

5. Accessing other folders: The folder command can be used to access folders of mail files. Note
that folders are created by you for organizational purposes. It is up to you to remember where
you have stored things!!

Access the new.folder with the command folder new.folder It should contain the files
you saved in the previous step.

6. Returning to a folder: Now that you know that mail messages are stored in text files, you can
return to any folder simply by using the folder command. To get back to your mbox folder, type
the command below:
7.
8. folder mbox

Parimal Sudas Page 93


9. Default folder location and folder shorthand notation: You can specify a directory where mail
folders are located by default. This requires a few setup details however.
1. First, get out of mail. Use the x or q command.
2. Create a folder directory. For example, use the command mkdir Mail
3. Set a pointer to this location. This can be done several ways. For this exercise, issue the
command setenv folder Mail

Start up mail with your mbox folder using the command mail -f mbox

Mail provides a shorthand for saving files into folders. Since you have done the necessary
setup, you can abbreviate the folder pathname specification with a plus sign (+). Save a
couple files with the command s +dakine

Now access this folder by the mail folder shorthand: folder +dakine You should see the
mail messages you saved from the previous step.

Experiment more if you wish. When you're done, exit mail with the q command. Note
that if you list the contents of your Mail subdirectory, you will see the folder you created
above.

10. Return to the tutorial to learn about the next section before proceeding.

Customizing Your Mail Environment

1. Examine your system's default mail configuration options with the command
2.
3. cat /usr/lib/Mail.rc

4. Begin an editing session and create a new file in your home directory called .mailrc - note that
it's name begins with a "dot", so that it will be a "hidden" file.
5. In your .mailrc file, specify some mail options. To begin with, you may wish to try the example
from the tutorial:
6.
7. # Simple .mailrc file
8. #
9. set ask askcc EDITOR=/source/local/bin/pico folder=Mail
10. set PAGER=more crt=20

11. Try mail now. Determine how the options in your .mailrc file affect your mail session.
12. Return to the tutorial to learn about the next section before proceeding.

Parimal Sudas Page 94


Pine: One Alternative to UNIX Mail
This exercise will acquaint you with the basics of the pine mail system. Pine includes many additional
features not reviewed here. It is assumed that these can be learned "on your own" since pine is so easy
to use and its online help is so complete.

1. Start pine: Make sure that you are in your home directory. Then type the command pine. Since
this is your first session, you will receive a screen full of information from pine. Read the
information carefully. Two important points to remember are mentioned:
o pine will create a subdirectory called mail in your home directory. This is where all of
your pine related mail will be kept.
o pine will automatically create a pine configuration file for you called .pinerc
2. Main Menu: After reading the opening message, press any key to continue. You should then see
the pine main menu. Take a moment to familiarize yourself with this menu.

You may also see a message about INBOX. This is what pine calls your incoming
mailbox. If you had any messages left there from the previous exercises, pine will notify
you. It will also tell you if there are none.

3. Online documentation: Pine includes an online manual. From the Main Menu, type the help
command ? to access the built in documentation. Notice the commands which appear at the
bottom of the screen. Press the space bar to see the next page. Read at least several pages of
the documentation and then type M to return to the Main Menu.
4. Compose a message: From the Main Menu, type C to begin composing a mail message. You will
immediately enter the compose screen. Notice the new commands which appear at the bottom
of the screen. In particular, notice that they are all "Control" character commands. Pine uses the
"caret" character (^) to designate CTRL. You may also recognize that these commands are
actually pico editor commands. Pine uses pico by default.

Notice that the "To:" line is highlighted. This tells you that pine is ready to have you type
in the email address of this message's recipient. Send the message to yourself, being sure
to substitute your userid for "studntXX" and your machine name for
"nodeX.class.mhpcc.edu" as you did in the previous mail exercises:

studntXX@nodeX.class.mhpcc.edu

Fill in the Subject: field and then type a couple of lines of message. When you're ready to send
the message, type the ^X command to send it. Pine will prompt you for confirmation - type y to
confirm. The message will be sent and you will be returned to the Main Menu.

Send at least three additional messages to yourself. Notice that pine will notify you
whenever a message arrives.

5. Getting help: Pine includes an excellent, context-sensitive help system. As an example, enter the
"Compose Message" screen. Move your cursor to various fields on the screen, such as the "To:"

Parimal Sudas Page 95


field, the "Subject:" field, etc. As you do this, get help on each field with the ^G command. Take
a few moments to read the help. To exit help, use the E command.

When you're done exploring the help for the compose screen, use the ^C command to
cancel the compose and return to the Main Menu.

6. Reading your mail: Your incoming mail is kept in pine's INBOX folder. By default, this is the
current folder. From the Main Menu, view the INBOX index with the I command. You will
immediately go to the folder index screen. The messages you sent previously should be visible
now.

The current message will be highlighted. Press the Return key to read it. The message
will display, as will new command options. After reading the message, move to the next
message by typing the N command.

Try accessing the help screen by typing the ? command. Type the E command to exit
help.

You can return to your folder index when you are done reading mail messages by using
the I command. Try this. Then use the up and down arrow keys to select different mail
messages. Notice how the index changes as you read messages (the N - new message
indicator is removed after a message is read).

7. Saving mail to a folder: Pine allows you to create and use folders for organizing your mail in
much the same way as UNIX mail. Try saving a couple messages to a new folder by following the
steps below:

1. Go to the INBOX folder index screen if you are not already there
2. Select any message to save by using your up/down arrow keys to highlight the message
3. Type the S command. You will be prompted to enter the name of the folder. Type the
name new.folder
4. You should then see a message that says "Folder "new.folder" doesn't exist. Create? (y/
n) [y]:" - type y to confirm.
5. Pine will copy the message to the folder (kept in the mail subdirectory). You will then
see an informational message which says " [Message 2 copied to folder "new.folder"
and marked deleted]".

Pine assumes that once you save a message to a folder, it is no longer needed and
so, marks it for deletion. You can "undelete" the message by simply typing the U
command.

6. Save at least one other message to the same folder. Notice that since this folder now
exists, you won't see the same prompts as before.
7. Go back to the Main Menu by typing the M command.
2. Changing folders: Pine makes moving between folders very easy. Follow the steps below to see
for yourself.

Parimal Sudas Page 96


1. Go to the Main Menu if you are not already there. Then use the L command to view a
list of your available folders. You will immediately go to the folder list screen.
2. Review the folder list screen. You should see four folders, including the folder
"new.folder" which you just created. The other folders, INBOX, sent-mail and saved-
messages are created by pine automatically.
3. Use the right arrow key until the folder "new.folder" is selected/highlighted. Press the
Return key to enter that folder. You should see an index of the messages you previously
saved.
4. Type the O command to see a few additional commands. Notice the L command. Using
this command will take you back to the folder list screen. Go ahead and try it.
5. Now use your left arrow key to select the INBOX folder. Press the Return key when it is
selected. You will now be in your INBOX folder again.
3. Quitting pine: You can exit your pine session at just about any point by typing the Q command.
Pine will "clean up" the INBOX by removing messages marked for deletion (it will ask for your
confirmation first) and then save the remaining messages in the INBOX folder.
4. Customizing pine: You can edit the .pinerc file which pine automatically created for you to
change certain aspects of pine's behavior. This exercise is left up to the reader.

Common UNIX Utilities

Alphabetical List

• addbib - create or extend a bibliographic database


• apropos - locate commands by keyword lookup
• ar - create library archives, and add or extract files
• at - execute a command or script at a specified time
• awk - pattern scanning and processing language
• banner - display a string in large letters
• basename - display portions of pathnames and filenames
• batch - runs jobs when the system load level permits
• biff - give notice of incoming mail messages
• cal - display a calendar
• calendar - a simple reminder service
• cancel - cancel requests to a printer
• cat - concatenate and display
• cb - a simple C program beautifier
• cc - C compiler
• cd - change working directory
• checknr - check nroff and troff input files; report possible errors
• checkeq - checks documents formatted with memorandum macros
• chgrp - change the group ownership of a file
• chmod - change the permissions mode of a file
• clear - clear the terminal screen
• cmp - perform a byte-by-byte comparison of two files
Parimal Sudas Page 97
• colcrt - filter nroff output for a terminal lacking overstrike capability
• comm - selects or rejects lines common to two sorted files
• compress - compress files (see uncompress also)
• cp - copy files
• cpio - copy file archives in and out
• cpp - the C language preprocessor
• csh - a shell with a C-like syntax and advanced interactive features
• ctags - create a tags file for use with ex and vi
• cut - Writes out selected bytes, characters, or fields from each line of a file
• date - display or set the date
• dbx - source-level debugger
• deroff - remove nroff, troff, tbl and eqn constructs
• df - report free disk space on file systems
• diff - display line-by-line differences between pairs of text files
• du - display the number of disk blocks used per directory or file
• e - starts the INed editor
• echo - echo arguments to the standard output
• ed, red - basic line editor
• edit - provides a simple line editor for the new user
• eqn - formats mathematical text for the troff command.
• ex - edits lines interactively, with a screen display
• expand - expand TAB characters to SPACE characters (see unexpand)
• expr - evaluate arguments as a logical, arithmetic, or string expression
• false - provide truth values (see true also)
• file - determine the type of a file by examining its contents
• find - find files by name, or by other characteristics
• finger - display information about users
• fmt - formats mail messages prior to sending
• fold - folds long lines for finite-width output device
• ftp - file transfer program
• gprof - display call-graph profile data
• grep - search a file for a string or regular expression
• groups - display a user's group memberships
• head - display first few lines of specified files
• hostname - set or print name of current host system
• indent - indent and format a C program source file
• install - install files
• join - relational database operator
• kill - send a signal to a process, or terminate a process
• last - indicate last logins by user or terminal
• ld - link editor
• leave - remind you when you have to leave
• lex - lexical analysis program generator
• lint - a C program verifier
• ln - make hard or symbolic links to files
• login - log in to the system
• look - find words in the system dictionary or lines in a sorted list

Parimal Sudas Page 98


• lookbib - find references in a bibliographic database
• lorder - find an ordering relation for an object library
• lp - send requests to a printer
• lpq - display the queue of printer jobs
• lpr - send a job to the printer
• lprm - remove jobs from the printer queue
• ls - list the contents of a directory
• mail, Mail - read or send mail messages
• make - maintain, update, and regenerate related programs and files
• man - display reference manual pages
• mesg - permit or deny messages on the terminal
• mkdir - make a directory
• mkstr - create an error message file by massaging C source files
• more - browse or page through a text file
• mv - move or rename files
• nice - run a command at low priority
• nm - print symbol name list
• neqn - formats mathematical text for the nroff command.
• nroff - format documents for display or line-printer
• od - octal, decimal, hexadecimal, and ascii dump
• page - browse or page through a text file
• passwd - change local password information
• paste - joins lines from one or more files
• pr - prepare files for printing, perhaps in multiple columns
• prof - display profile data
• ps - display the status of current processes
• pwd - display the pathname of the current working directory
• ranlib - convert archives to random libraries
• rcp - remote file copy
• rev - reverse the order of characters in each line
• rlogin - remote login
• rm - remove files or directories
• rmdir - remove directories
• roffbib - format and print a bibliographic database
• rsh - remote shell
• rup - show host status of local machines RPC version
• ruptime - show host status of local machines
• rusers - who's logged in on local machines RPC version
• rwall - write to all users over a network
• rwho - who's logged in on local machines
• sccs - front end for the Source Code Control System SCCS. Includes a number of related
commands with their own man pages.
• script - make typescript of a terminal session
• sed - stream editor
• sh - shell, the standard UNIX system command interpreter and command-level language
• size - display the size of an object file
• sleep - suspend execution for a specified interval

Parimal Sudas Page 99


• sort - sort and collate lines
• sortbib - sort a bibliographic database
• spell - report spelling errors
• split - split a file into pieces
• strings - find printable strings in an object file or binary
• strip - remove symbols and relocation bits from an object file
• stty - sets, resets, and reports workstation operating parameters
• su - super-user, temporarily switch to a new user ID
• tabs - set tab stops on a terminal
• tail - display the last part of a file
• talk - talk to another user
• tar - create tape archives, and add or extract files
• tbl - format tables for nroff or troff
• tee - replicate the standard output
• telnet - user interface to a remote system using the TELNET protocol
• test - evaluates conditional expressions
• tftp - trivial file transfer program
• time - time a command
• touch - update the access and modification times of a file
• troff - typeset or format documents
• true - provide truth values (see false also)
• tsort - topological sort
• tty - display the name of the terminal
• ul - do underlining
• uncompress - uncompress files (see compress also)
• uniq - remove or report adjacent duplicate lines
• units - conversion program
• uptime - show how long the system has been up
• users - display a compact list of users logged in
• uucp - system to system copy
• unexpand - restores TAB characters from SPACE characters (see expand)
• vacation - reply to mail automatically
• vi, vedit - visual display editor
• view - starts the vi editor in read-only mode
• w - who is logged in, and what are they doing
• wait - wait for a process to finish
• wall - write to all users logged in
• wc - display a count of lines, words and characters
• whatis - describes what function a command performs
• whereis - locates source, binary, or manual for program
• which - locates a program file, including aliases and paths
• who - identifies the users currently logged in
• whoami - display your username
• write - send messages to other users on the system in real time
• xargs - constructs parameter lists and runs commands
• xstr - extract strings from C programs to implement shared strings
• yacc - yet another compiler-compiler: parsing program generator

Parimal Sudas Page 100


• yes - outputs an affirmative response repetitively
• zcat - display compressed files

Functional List

• Files and Directories


• Information
• Mail
• Miscellaneous
• Printing
• Programming Tools
• Shells, Job Control and Access
• Terminal Related
• Text Formatting and Editing
• User Information and Communications
• uucp / BNU

Files and Directories

• ar - create library archives, and add or extract files


• basename - display portions of pathnames and filenames
• cat - concatenate and display
• cd - change working directory
• chgrp - change the group ownership of a file
• chmod - change the permissions mode of a file
• cmp - perform a byte-by-byte comparison of two files
• comm - selects or rejects lines common to two sorted files
• compress - compress files (see uncompress also)
• cp - copy files
• cpio - copy file archives in and out
• csh - a shell with a C-like syntax and advanced interactive features
• cut - Writes out selected bytes, characters, or fields from each line of a file
• df - report free disk space on file systems
• diff - display line-by-line differences between pairs of text files
• du - display the number of disk blocks used per directory or file
• expand - expand TAB characters to SPACE characters (see unexpand)
• file - determine the type of a file by examining its contents
• find - find files by name, or by other characteristics
• install - install files
• ftp - file transfer program
• grep - search a file for a string or regular expression
• head - display first few lines of specified files
• ln - make hard or symbolic links to files
• ls - list the contents of a directory
• mkdir - make a directory
• more - browse or page through a text file
Parimal Sudas Page 101
• mv - move or rename files
• od - octal, decimal, hexadecimal, and ascii dump
• page - browse or page through a text file
• paste - joins lines from one or more files
• pwd - display the pathname of the current working directory
• rcp - remote file copy
• rev - reverse the order of characters in each line
• rm - remove files or directories
• rmdir - remove directories
• size - display the size of an object file
• sort - sort and collate lines
• spell - report spelling errors
• split - split a file into pieces
• strings - find printable strings in an object file or binary
• strip - remove symbols and relocation bits from an object file
• tail - display the last part of a file
• tar - create tape archives, and add or extract files
• tee - replicate the standard output
• tftp - trivial file transfer program
• touch - update the access and modification times of a file
• uncompress - uncompress files (see compress also)
• uniq - remove or report adjacent duplicate lines
• unexpand - restores TAB characters from SPACE characters (see expand)
• wc - display a count of lines, words and characters
• zcat - display compressed files

Information

• apropos - locate commands by keyword lookup


• hostname - set or print name of current host system
• man - display reference manual pages
• rup - show host status of local machines RPC version
• ruptime - show host status of local machines
• uptime - show how long the system has been up
• whatis - describes what function a command performs
• whereis - locates source, binary, or manual for program
• which - locates a program file, including aliases and paths

Mail

• biff - give notice of incoming mail messages


• mail, Mail - read or send mail messages
• vacation - reply to mail automatically

Miscellaneous

• banner - display a string in large letters

Parimal Sudas Page 102


• cal - display a calendar
• calendar - a simple reminder service
• date - display or set the date
• join - relational database operator
• echo - echo arguments to the standard output
• look - find words in the system dictionary or lines in a sorted list
• leave - remind you when you have to leave
• script - make typescript of a terminal session
• tsort - topological sort
• units - conversion program
• yes - outputs an affirmative response repetitively

Printing

• cancel - cancel requests to a printer


• lp - send requests to a printer
• lpq - display the queue of printer jobs
• lpr - send a job to the printer
• lprm - remove jobs from the printer queue
• pr - prepare files for printing, perhaps in multiple columns

Programming Tools

• ar - create library archives, and add or extract files


• awk - pattern scanning and processing language
• cb - a simple C program beautifier
• cc - C compiler
• cpp - the C language preprocessor
• dbx - source-level debugger
• indent - indent and format a C program source file
• gprof - display call-graph profile data
• ld - link editor
• lex - lexical analysis program generator
• lint - a C program verifier
• lorder - find an ordering relation for an object library
• make - maintain, update, and regenerate related programs and files
• mkstr - create an error message file by massaging C source files
• nm - print symbol name list
• prof - display profile data
• ranlib - convert archives to random libraries
• sccs - front end for the Source Code Control System SCCS. Includes a number of related
commands with their own man pages.
• size - display the size of an object file
• strip - remove symbols and relocation bits from an object file
• xstr - extract strings from C programs to implement shared strings
• yacc - yet another compiler-compiler: parsing program generator

Parimal Sudas Page 103


Shells, Job Control and Access

• at - execute a command or script at a specified time


• batch - runs jobs when the system load level permits
• expr - evaluate arguments as a logical, arithmetic, or string expression
• false - provide truth values (see true also)
• kill - send a signal to a process, or terminate a process
• login - log in to the system
• nice - run a command at low priority
• passwd - change local password information
• ps - display the status of current processes
• rlogin - remote login
• rsh - remote shell
• sh - shell, the standard UNIX system command interpreter and command level language
• sleep - suspend execution for a specified interval
• su - super-user, temporarily switch to a new user ID
• telnet - user interface to a remote system using the TELNET protocol
• test - evaluates conditional expressions
• time - time a command
• true - provide truth values (see false also)
• wait - wait for a process to finish
• xargs - constructs parameter lists and runs commands

Terminal Related

• clear - clear the terminal screen


• mesg - permit or deny messages on the terminal
• stty - sets, resets, and reports workstation operating parameters
• tabs - set tab stops on a terminal
• tty - display the name of the terminal

Text Formatting and Editing

• addbib - create or extend a bibliographic database


• checknr - check nroff and troff input files; report possible errors
• checkeq - checks documents formatted with memorandum macros
• colcrt - filter nroff output for a terminal lacking overstrike capability
• ctags - create a tags file for use with ex and vi
• deroff - remove nroff, troff, tbl and eqn constructs
• e - starts the INed editor
• ed, red - basic line editor
• edit - provides a simple line editor for the new user
• eqn - formats mathematical text for the troff command.
• ex - edits lines interactively, with a screen display
• fmt - formats mail messages prior to sending
• fold - folds long lines for finite-width output device
• lookbib - find references in a bibliographic database

Parimal Sudas Page 104


• neqn - formats mathematical text for the nroff command.
• nroff - format documents for display or line-printer
• roffbib - format and print a bibliographic database
• sed - stream editor
• sortbib - sort a bibliographic database
• tbl - format tables for nroff or troff
• troff - typeset or format documents
• ul - do underlining
• vi, vedit - visual display editor
• view - starts the vi editor in read-only mode

User Information and Communication

• finger - display information about users


• groups - display a user's group memberships
• last - indicate last logins by user or terminal
• rusers - who's logged in on local machines RPC version
• rwall - write to all users over a network
• rwho - who's logged in on local machines
• talk - talk to another user
• users - display a compact list of users logged in
• w - who is logged in, and what are they doing
• wall - write to all users logged in
• write - send messages to other users on the system in real time
• who - identifies the users currently logged in
• whoami - display your username

uucp / BNU

• uucp - system to system copy


• uuencode, uudecode - encode a binary file, or decode its ASCII representation
• uulog - provides information about BNU file-transfer activities on a system.
• uuname - provides information about other systems accessible to the local system
• uusend - send a file to a remote host
• uux - runs a command on another UNIX-based system

What is a Shell Script?


• A shell script is an executable file which contains shell commands. The script acts as a "program"
by sequentially executing each command in the file.
• Each of the 5 common shells has its own scripting language. There are similarities between the
languages, but also differences.
• A scripting language consists of control structures, shell commands, expressions and variables.
• If a shell script written in a given scripting language must run under the appropriate shell, the
first line of the script should specify the shell it must run under. For example, a C shell script
should have as the first line:
Parimal Sudas Page 105

• #!/bin/csh

• Script files should be given "execute" file permission with the chmod command:

• chmod u+x myscript

• A simple shell script which will run under any of the 5 shells appears below. This script simply
displays a greeting and the date/time. Comments are preceeded with a pound sign (#):

• #Simple Script
• #
• echo 'Welcome to the world of script files'
• date

Expressions
• Expressions are statements, composed of constants, variables and operators, which are
evaluated to determine a result. Expressions can be either mathematical or logical.

Example 1: Mathematical expression, where "a" and "t" are variables, "3" and "4" are
constants, and "=" and "+" are operators.

a = 3 + 4t

Example 2: Logical expression, which evaluates to either "true" or "false". The string
"exit" is a constant, "var" is a variable, and "(", ")" and "==" are operators.

($var == exit)

• Shell scripts commonly use expressions. Each shell has its own rules for writing expressions,
however.
• The C Shell recognizes the following operators, in order of precedence.

• () - parenthesis - change order of evaluation
• - - unary minus/negation
• ~ - one's complement

Parimal Sudas Page 106


• ! - logical negation
• % - remainder
• / - divide
• * - multiply
• - - subtract
• + - addition
• >> - shift right
• << - shift left
• > - greater than
• < - less than
• >= - greater than or equal
• <= - less than or equal
• != - not equal to (strings)
• == - equal to (strings)
• & - bitwise AND
• ^ - bitwise exclusive OR
• | - bitwise inclusive OR
• && - logical AND
• || - logical OR

Control Structures
Script languages make use of programming control structures, such as "if" statements and "loops".
Those for C Shell are described below.

if

Used to test an expression and then conditionally execute a command. If the specified
expression evaluates true, then the single command with arguments is executed.
Command must be a simple command, not a pipeline, a command list, or a parenthesized
command list.

Syntax:

if (expr) command [arguments]

Example:

#!/bin/csh
if ($#argv == 0) echo There are no arguments

Parimal Sudas Page 107


In addition to the C Shell's logical expressions, you can use expressions that return a
value based upon the status of a file. For example:

if (-e myfile) echo myfile already exists

The possible file status expressions are:

d - file is a directory
e - file exists
f - file is an ordinary file
o - user owns the file
r - user has read access to the file
w - user has write access to the file
x - user has execute access to the file
z - file is zero bytes long

if / then / else

Used to test multiple conditions and to execute more than a single command per
condition. If the specified expr is true then the commands to the first else are executed;
otherwise if expr2 is true then the commands to the second else are executed, etc. Any
number of else-if pairs are possible; only one endif is needed. The else part is likewise
optional.

The words else and endif must appear at the beginning of command lines; the if must
appear alone on its command line or immediately after an else.

Syntax:

if (expr) then
commands
else if (expr2) then
commands
else
commands
endif

Example:

#!/bin/csh
if ($#argv == 0) then
echo "No number to classify"
else if ($#argv > 0) then

Parimal Sudas Page 108


set number = $argv[1]
if ($number < 0) then
@ class = 0
else if (0 <= $number && $number < 100) then
@ class = 1
else if (100 <= $number && $number < 200) then
@ class = 2
else
@ class = 3
endif
echo The number $number is in class $class
endif

foreach / end

The foreach statement is a type of loop statement. The variable name is successively set
to each member of wordlist and the sequence of commands until the matching end
statement are executed. Both foreach and end must appear alone on separate lines.

Syntax:

foreach name (wordlist)


commands
end

Example:

#!/bin/csh
foreach color (red orange yellow green blue)
echo $color
end

while / end

The while statement is another type of loop statement. Statements within the while/end
loop are conditionally executed based upon the evaluation of the expression. Both while
and end must appear alone on separate lines.

Syntax:

while (expression)
commands

Parimal Sudas Page 109


end

Example:

#!/bin/csh
set word = "anything"
while ($word != "")
echo -n "Enter a word to check (Return to exit): "
set word = $<
if ($word != "") grep $word /usr/share/dict/words
end

break

Used to interrupt the execution of a foreach or while loop. Transfers control to the statement
after the end statement, thus terminating the loop. If there are other commands on the same line
as a break statement, they will be executed before the break occurs. Multi-level breaks are thus
possible by writing them all on one line.

Syntax:

break

Example:

#!/bin/csh
foreach number (one two three exit four)
if ($number == exit) then
echo reached an exit
break
endif
echo $number
end

continue

Used to interrupt the execution of a foreach or while loop. Transfers control to the end statement,
thus continuing the loop. If there are other commands on the same line as a continue statement,
they will be executed before the continue occurs.

Syntax:

Parimal Sudas Page 110


continue

Example:

#!/bin/csh
foreach number (one two three exit four)
if ($number == exit) then
echo reached an exit
continue
endif
echo $number
end

goto

The goto statement transfers control to the statement beginning with label:

Syntax:

goto label

Example:

#!/bin/csh
if ($#argv != 1) goto error1
if ($argv[1] < 6) goto error2
goto OK

error1:
echo "Invalid - wrong number or no arguments"
echo "Quitting"
exit 1

error2:
echo "Invalid argument - must be greater than 5"
echo "Quitting"
exit 1

OK:
echo "Argument = $argv[1]"
exit 1

Parimal Sudas Page 111


switch / case / breaksw / endsw

The switch structure permits you to set up a series of tests and conditionally executed
commands based upon the value of a string. If none of the labels match before a `default'
label is found, then the execution begins after the default label.

Each case label and the default label must appear at the beginning of a line. The
command breaksw causes execution to continue after the endsw. Otherwise control may
fall through case labels and default labels. If no label matches and there is no default,
execution continues after the endsw.

Syntax:

switch (string)
case str1:
commands
breaksw
case str2:
commands
breaksw
...
default:
commands
breaksw
endsw

Example:

#!/bin/csh
if ($#argv == 0 ) then
echo "No arguments supplied...exiting"
exit 1
else
switch ($argv[1])
case [yY][eE][sS]:
echo Argument one is yes.
breaksw
case [nN][oO]:
echo Argument one is no.
breaksw
default:
echo Argument one is neither yes nor no.
breaksw
endsw
endif

Parimal Sudas Page 112


Interrupt handling

The onintr statement transfers control when you interrupt (CTRL-C) the shell script. Control is
transferred to the statement beginning with label:

Can be useful for gracefully cleaning up temporary files and exiting a program should it be
interrupted.

Syntax:

onintr label

Example:

#!/bin/csh
onintr close
while (1 == 1)
echo Program is running
sleep 2
end

close:
echo End of program

Miscellaneous
Miscellaneous tasks for C Shell programming are described below.

Using quotes
The shell uses both single (') quotes and double (") quotes. They have different effects.

Single quotes:

o allow inclusion of spaces


o prevent variable substitution
o permit filename generation

Double quotes:

o allow inclusion of spaces


o permit variable substitution
o permit filename generation

Parimal Sudas Page 113


Example 1: Variable substitution

#!/bin/csh
set opt=-l
set x1='ls $opt'
echo $x1
set x2="ls $opt"
echo $x2

Will produce the output:


ls $opt
ls -l

Example 2: Filename generation

#!/bin/csh
set ls1='some files: [a-z]*'
echo $ls1

set ls2="some files: [a-z]*"


echo $ls2

Sample output (identical):


some files: csh.html images man misc other.materials
some files: csh.html images man misc other.materials

Storing the output of a command

The shell uses backquotes to obtain the output of the command enclosed within the backquotes.
This output can be stored within an array variable. Each element can then be indexed and
processed as required.

Syntax:

set variable = `command`

Example:

#!/bin/csh
set date_fields=`date`
echo $date_fields
echo $date_fields[1]
echo $date_fields[2]
foreach field(`date`)
echo $field
end

Sample output:

Parimal Sudas Page 114


Thu Mar 9 22:25:45 HST 1995
Thu
Mar
Thu
Mar
9
22:25:45
HST
1995

Reading user input

Depending on your system, you can use either "$<" or the output of the "head -1" command to
read stdin into a variable. Note that if you use the "head -1" command, it must be enclosed in
backquotes.

Note: Be careful on making sure that you use "$<" and not "<$". The latter case will usually
cause your script to fail.

Syntax:

set variable = $<


- or -
set variable = `head -1`

Example:

#!/bin/csh
echo -n Input your value:
set input = $<
echo You entered: $input

- or -

#!/bin/csh
echo -n Input your value:
set input = `head -1`
echo You entered: $input

Introduction to UNIX
Shell Script Exercises

Parimal Sudas Page 115


Simple Script

1. Open a new window or use an existing window. Change directory to the Scripts exercise
directory:
2.
3. cd ~/Scripts

4. Edit a new file - call it simple. Include the following lines in your simple file:
5.
6. #!/bin/csh
7. #
8. #Simple Script
9. #
10. echo Welcome to the world of script files
11. echo -n "The current time and date are: "
12. date

Save your file and exit the editor.

13. Make this file world executable. Check its permissions to make sure:
14.
15. chmod a+x simple
16. ls -l simple

17. Execute the file by invoking its name: simple. Observe the output. How does the -n option
modify the output from echo?
18. Return to the tutorial to learn about the next section before proceeding.

Expressions

1. Display the file simple.2 which is already provided for you in your ~/Scripts directory. Note the
use of a couple simple expressions.
2. Check to make sure the file is executable. If it isn't, then use the chmod to make it executable at
least by you.
3.
4. ls -l simple.2
5. chmod u+x

6. Execute the example file by invoking its name: simple.2 and observe the output.
7. Now, edit the file and add the lines below. When finished, save the file and try executing it
again.
8.
9. @ count = 1
10. echo Count begins as $count
11. @ count = $count + 100

Parimal Sudas Page 116


12. echo Count plus 100 = $count

13. Return to the tutorial to learn about the next section before proceeding.

if

1. Create a new file called simple.3 which include these lines:


2.
3. #!/bin/csh
4. if ($#argv == 0) echo There are no arguments
5. if ($#argv != 0) echo There are $#argv arguments

6. After saving the file, make it executable and then run it as shown:
7.
8. chmod +x simple.3
9. simple.3

10. Now try running it several more times, but with a different number of arguments each time. For
example:
11.
12. simple.3 one two
13. simple.3 a b c 3 4
14. simple.3 9*3 65 100.34 - will cause an error - why?
15. simple.3 '9*3' 65 100.34
16. simple.3 '10 disc write' - why is this considered 1?

17. Edit the file again, adding the following lines:


18.
19. if (-e $1) echo The file: $1 exists.
20. if (! -e $1) echo The file: $1 does not exist.

21. Now execute the file with a filename as the only argument and observe the output:
22.
23. simple.3 nosuchfile
24. simple.3 simple.3
25. simple.3 simple

26. Return to the tutorial to learn about the next section before proceeding.

Parimal Sudas Page 117


if then else

1. Display the file simple.4 which is already provided for you in your ~/Scripts directory. It is the
same as the one from the tutorial. Attempt to understand what the expressions are evaluating
and the logic of the if-then-else nesting.
2. Make sure the file is executable (you know how to do this by now) and then try running it with
different arguments. Compare the output with the script's logic as you understand it. Do they
agree?
3.
4. simple.4 34
5. simple.4 199
6. simple.4 1000
7. simple.4 -33
8. simple.4

9. Return to the tutorial to learn about the next section before proceeding.

foreach

1. Display the file simple.5 which is already provided for you in your ~/Scripts directory.
Understand what it does and its use of the foreach construct.
2. Make sure the file is executable (you know how to do this by now) and execute it. Does it
correctly determine your login machine?

while

1. Now create your own executable script by copying the while loop example from the tutorial. It is
reproduced below for convenience:
2.
3. #!/bin/csh
4. set word = "anything"
5. while ($word != "")
6. echo -n "Enter a word to check (Return to exit): "
7. set word = $<
8. if ($word != "") grep $word /usr/share/dict/words
9. end

10. Give it execute permission and then run it. What does it do?
11. Return to the tutorial to learn about the next section before proceeding.

switch / case / breaksw / endsw

1. Display the file simple.6 which is already provided for you in your ~/Scripts directory. This file is
a little lengthier than previous files. Notice the use of the switch construct.

Parimal Sudas Page 118


2. Make sure the file is executable (you know how to do this by now) and execute it.
3. Now edit the simple.6 file and add the necessary commands to handle the month of Dec. Re-
execute the script. Does it still work?

Network Related Utilities


Several UNIX utilities are especially useful for users computing in a networked, distributed
environment. Additional tools for System Administrators are available but not discussed here.

talk
• The talk command allows two users on the same host or on different hosts to have an
interactive conversation.
• The talk command opens both a send window and a receive window on each user's
display. Each user is then able to type into the send window while the talk command
displays what the other user is typing.
• A sample talk screen is available here.
• Using the talk command - some examples:

• talk kellyk - talk to a local user
• talk dale@wave.com - talk to a remote user

• Some notes about using talk:


o The user you wish to talk with must be logged on.
o The "mesg" command can be used to prevent others from "talking" to you. For
example: mesg n
o Talk may be disabled on other systems for security reasons.
• See the talk man page for details.

finger
• The finger command displays information about users on a given host. The host can be
either local or remote.
• Example 1: Show who is logged onto the system

finger - show all local logins


finger @wave.com - show remote system's logins

Login Name TTY Idle When Site Info


rjw Robert J West p0 7:11 Sat 10:32
mdine Marc Dine p1 7:11 Wed 09:46
zepht James S. Tallis p2 7:11 Wed 09:46

Parimal Sudas Page 119


bqs5 Barbara Baker p3 8:42 Sat 10:33
davek Dave Kiley p4 8:42 Sat 10:33

• Example 2: Show information about a specific user

finger ksmith - look for a local user


finger dale@wave.com - look for a remote user

Login name: dale In real life: Dale Smith


Directory: /u/ibm/dale Shell: /bin/csh
Project:
Parallel Programming for the masses. (Masses of what!)
Plan:

Think globally, act locally: install solar panels !

• If you create a .plan and/or .project file in your home directory and make them world
readable, they will appear in the Plan and Project fields of the finger output.
• Finger may be disabled on other systems for security reasons.
• See the finger man page for details.

ping
• The ping command sends an echo request to a network host. It is useful for:
o Determining the status of the network and various foreign hosts.
o Tracking and isolating hardware and software problems.
o Testing, measuring, and managing networks.
• The ping command sends one datagram per second and prints one line of output for every
response received. Round-trip times and packet loss statistics are calculated and
displayed.
• Example:
• % ping kanaha
• PING kanaha.mhpcc.edu: (164.122.27.33): 56 data bytes
• 64 bytes from 164.122.27.33: icmp_seq=0 ttl=254 time=3 ms
• 64 bytes from 164.122.27.33: icmp_seq=1 ttl=254 time=2 ms
• 64 bytes from 164.122.27.33: icmp_seq=2 ttl=254 time=2 ms
• 64 bytes from 164.122.27.33: icmp_seq=3 ttl=254 time=2 ms
• 64 bytes from 164.122.27.33: icmp_seq=4 ttl=254 time=2 ms
• 64 bytes from 164.122.27.33: icmp_seq=5 ttl=254 time=2 ms
• ^C
• ----kanaha.mhpcc.edu PING Statistics----
• 6 packets transmitted, 6 packets received, 0% packet loss
• round-trip min/avg/max = 2/2/3 ms

Parimal Sudas Page 120


• See the ping man page for details.

traceroute
• The traceroute command prints the route that IP packets take to a network host. It is
intended for use in network testing, measurement, and management.
• Example:
• % traceroute archie.rutgers.edu
• traceroute to dorm.Rutgers.EDU (128.6.18.15), 30 hops max, 40 byte
packets
• 1 B2_IGSL_01 (129.24.96.1) 2 ms 2 ms 2 ms
• 2 FZ00_rtr_01 (129.24.56.1) 3 ms 2 ms 7 ms
• 3 msh (129.24.8.193) 5 ms 7 ms 4 ms
• 4 198.83.5.5 (198.83.5.5) 7 ms 4 ms 7 ms
• 5 hssi3-0.cnss116.Albuquerque.t3.ans.net (192.103.74.41) 5 ms 4 ms
6 ms
• 6 mf-0.cnss112.Albuquerque.t3.ans.net (140.222.112.222) 4 ms 4 ms
4 ms
• 7 t3-0.cnss64.Houston.t3.ans.net (140.222.64.1) 30 ms 30 ms 30 ms
• 8 t3-0.cnss80.St-Louis.t3.ans.net (140.222.80.1) 47 ms 47 ms 46 ms
• 9 t3-1.cnss25.Chicago.t3.ans.net (140.222.25.2) 54 ms 52 ms 53 ms
• 10 t3-0.cnss40.Cleveland.t3.ans.net (140.222.40.1) 60 ms 59 ms 59 ms
• 11 t3-1.cnss48.Hartford.t3.ans.net (140.222.48.2) 73 ms 78 ms 74 ms
• 12 t3-2.cnss32.New-York.t3.ans.net (140.222.32.3) 78 ms 76 ms 76 ms
• 13 t3-0.enss137.t3.ans.net (140.222.137.1) 79 ms 80 ms 86 ms
• 14 fenchurch-gateway.jvnc.net (192.12.211.65) 83 ms 80 ms 84 ms
• 15 airport2-gateway.jvnc.net (130.94.9.250) 84 ms 86 ms 88 ms
• 16 airport1-gateway.jvnc.net (130.94.7.1) 85 ms 92 ms 84 ms
• 17 rutgers-gateway.jvnc.net (130.94.7.10) 89 ms 86 ms 90 ms
• 18 rucs-gw.rutgers.edu (128.6.21.7) 94 ms 104 ms 95 ms
• 19 dorm.rutgers.edu (128.6.18.15) 92 ms 93 ms 91 ms

• Warning: Because of the load traceroute imposes on the network, the traceroute
command should not be used during normal operations or from automated scripts.
• The traceroute utility may not be available on all systems.
• See the traceroute man page for details.

ftp
• ftp stands for File Transfer Protocol. File transfer provides a means for you to obtain
computer files (text, image, sound, etc.) from other computers over the network.

Parimal Sudas Page 121


• ftp can also be used to send (upload) files from your computer to another computer,
providing you have write permission or a real account on the machine you are uploading.
• The ftp utility has its own set of UNIX like commands which allow you to perform tasks
such as:
o Connect and login to a remote host
o Navigate directories
o List directory contents
o Put and get files
o Transfer files as ascii, ebcdic or binary
• A sample ftp session appears below. The commands which are entered by the user are in
bold type.
• kanaha% ftp makena.mhpcc.edu
• Connected to makena.mhpcc.edu.
• 220 makena.mhpcc.edu FTP server (Version 4.9 Thu Sep 2 20:35:07 CDT
1993)
• Name (makena.mhpcc.edu:jsmith): jsmith
• 331 Password required for jsmith.
• Password:
• 230 User jsmith logged in.
• ftp> dir
• 200 PORT command successful.
• 150 Opening data connection for /bin/ls.
• total 1464
• drwxr-sr-x 3 jsmith staff 1024 Mar 11 20:04 Mail
• drwxr-sr-x 2 jsmith staff 1536 Mar 3 18:07 Misc
• drwxr-sr-x 5 jsmith staff 512 Dec 7 10:59 OldStuff
• drwxr-sr-x 2 jsmith staff 1024 Mar 11 15:24 bin
• drwxr-sr-x 5 jsmith staff 3072 Mar 13 16:10 mpl
• -rw-r--r-- 1 jsmith staff 209671 Mar 15 10:57 myfile.out
• drwxr-sr-x 3 jsmith staff 512 Jan 5 13:32 public
• drwxr-sr-x 3 jsmith staff 512 Feb 10 10:17 pvm3
• 226 Transfer complete.
• ftp> cd mpl
• 250 CWD command successful.
• ftp> dir
• 200 PORT command successful.
• 150 Opening data connection for /bin/ls.
• total 7320
• -rw-r--r-- 1 jsmith staff 1630 Aug 8 1994 dboard.f
• -rw-r----- 1 jsmith staff 4340 Jul 17 1994 vttest.c
• -rwxr-xr-x 1 jsmith staff 525574 Feb 15 11:52 wave_shift
• -rw-r--r-- 1 jsmith staff 1648 Aug 5 1994 wide.list
• -rwxr-xr-x 1 jsmith staff 4019 Feb 14 16:26 fix.c
• 226 Transfer complete.
• ftp> get wave_shift
• 200 PORT command successful.
• 150 Opening data connection for wave_shift (525574 bytes).
• 226 Transfer complete.

Parimal Sudas Page 122


• 528454 bytes received in 1.296 seconds (398.1 Kbytes/s)
• ftp> quit
• 221 Goodbye.

• Many computers on the Internet permit anonymous ftp . You can login to these machines
without a real account, to obtain files which have been made publicly available.
Typically, the user name anonymous is used, coupled with your email address as the
password.
• Anonymous ftp is usually restricted so that users can only see what the server permits
them to see. Anonymous users do not have full privileges as would a user with a real
computer account.
• See the ftp man page for details.
• Begin the ftp exercise.

telnet
• Telnet is a utility that allows a computer user at one site to make a connection, login and
then conduct work on a computer at another site. For example, you can use the telnet
command to run a program in your directory on a supercomputer thousands of miles
away.
• Telnet is used to access many of the Internet resources, such as databases, libraries and
computers
• Example telnet session:
• % telnet makena
• Trying...
• Connected to makena.mhpcc.edu.
• Escape character is '^]'.


• AIX Version 3
• (C) Copyrights by IBM and by others 1982, 1993.
• login: jsmith
• jsmith's Password:
• ***********************************************************************
***
• *
*
• *
*
• * WELCOME TO THE Maui High Performance Computing Center *
• *
*
• *
*

Parimal Sudas Page 123


• ***********************************************************************
***

• Last unsuccessful login: Fri Mar 3 12:01:09 HST 1995 on pts/0 from
kanaha.mhpcc.edu
• Last login: Wed Mar 8 18:33:27 HST 1995 on pts/10

• { do some work }

• makena% logout
• Connection closed.

• See the telnet man page for details.


• Begin the telnet exercise.

rlogin
rsh
rcp
• rlogin (remote login), rsh (remote shell) and rcp (remote copy) are three utilities which
allow you to perform tasks on other machines without requiring the usual login
authentication.
• All three utilities depend upon a .rhosts located in your home directory. The .rhosts file
contains the names of your "trusted" hosts and your userid on each of those hosts. An
example appears below:

• apache.unm.edu jsmith
• zeus.mit.edu jsmith
• athena.com smith
• fox.eeco.org smithj

• rlogin: Allows you to login to a remote machine. It is nearly identical to telnet in function
and appearance, however if your .rhosts file is setup accordingly, you will be able to
login to your account on another machine wihout having to enter a userid and password.
• rsh: The remote shell command can be used to execute a command on remote host or log
into remote host. With the proper .rhosts file, authentication is not required.
• Examples:

• rsh host2 - will connect to host2 for
• login
• rsh host2 df - check the amount of free
• disk space on remote host2

Parimal Sudas Page 124


• rsh host2 ps aux |grep jsmith - check for processes owned
• by jsmith on host2
• rsh host2 rm /tmp/myfile.old - remove a file in host2
• rsh host2 cat test1 ">>" test2 - append test1 file on remote
• host to test2 file on remote
• host
• rsh host2 cat test1 >> test2 - append test1 file on remote
• host to test2 file on local
• host

• rcp: Remote copy enables you to copy files between different systems. With the proper
.rhosts file, authentication is not required.
• Example:

• rcp localfile host2:/home/eng/journal

Introduction to UNIX
Network Related Utilities Exercises
ftp
Anonymous FTP will be used to connect to an Internet computer which contains an image file
representing a Van Gogh painting. The file will first be downloaded and then an image viewing utility will
be used to display the image file on your screen.

1. Create a new window or use an existing window. Type the following command in that window:
2.
3. ftp kanaha.mhpcc.edu

4. As the network connection is established with the server computer you will see several
messages appear on your screen. You will then be prompted to enter your Name. Type the
name anonymous and hit return.
5. You will then be prompted to enter a Password. Type the password guest . You will then see a
couple messages. At the bottom of the screen, you should see the prompt: ftp> . This means
that ftp is now ready to accept commands from you.
6. View the top level file directory by typing the command: dir . This shows a typical UNIX long
directory listing. The important column is the last one on the right which shows the file names.
The ls command can also be used to give a short directory listing.
7. Change directory to the pub subdirectory, list the files, and then change to the Misc
subdirectory and list its contents by using the following commands:
8.
9. cd pub

Parimal Sudas Page 125


10. dir
11. cd Misc
12. dir

13. You should see a file called starry.night.gif . If you do, you are now ready to download the file.
Use the command:
14.
15. get starry.night.gif

When the download is complete you will see a message that looks something like this:

226 Transfer complete.


273663 bytes received in 1.243 seconds (220.2 Kbytes/s)
ftp>

16. Quit your ftp session by typing the quit command.


17. The file which you downloaded is a GIF (Graphical Interchange Format) image file - a very
common file type for images on the Internet. Being able to view the file on your local computer
requires that you have software which can display GIF type files. One such UNIX utility is called
"xv". Use "xv" to display your downloaded file by typing the command:
18.
19. xv starry.night.gif

20. When you are done viewing your image, left-click on the image with your mouse and then type
the letter Q for quit.
21. This completes the FTP exercise. Return to the tutorial to learn about the next section before
proceeding.

telnet

The telnet utility will be used to connect to another machine and login.

1. Create a new window or use an existing window. Type the following command in that
window, substituting a classroom machine name for nodeXX (node1-node16). Please
use a machine other than the one you are currently logged into.
2.
3. telnet nodeXX.class.mhpcc.edu

4. You will be asked to login - use your assigned userid and password. Be sure to type n
when asked to start mosaic.

Parimal Sudas Page 126


5. After you login, list your home directory. Looks familiar? Because all of the classroom
machines share the same user filespace, you can log into any classroom machine and
have your files visible.

If you had an account on a non-MHPCC machine, your files there would local to
that system.

6. Use logout or exit to quit this telnet session and return to your original login machine.
7. This completes the telnet exercise. Return to the tutorial to learn about the next section
before proceeding.

rlogin, rcp, rsh

This exercise will familiarize you with the remote login, remote copy and remote shell
commands.

Creating a .rhosts file

1. Create a new window or use an existing window. Make sure that you are in your
home directory by typing the cd command.
2. Use an editor to open a file called .rhosts and add the following lines to this file,
being sure to substitute your student userid for "myuserid".

HINTS: You can type in all 16 lines if you want, OR, you could:

 Read in the file ~/Scripts/node.names and just add your userid to each
line
 Use your editor's "cut and paste" capabilities. Just type one line and
then cut and paste it 15 times. All you'll need to change then are the
line numbers.
 If you know how to use the mouse for cutting and pasting between
windows, it's even easier. Just cut from this window and paste into the
window which contains your editing session. Then change the
"myuserid" on each line.

node1.class.mhpcc.edu myuserid
node2.class.mhpcc.edu myuserid
node3.class.mhpcc.edu myuserid
node4.class.mhpcc.edu myuserid
node5.class.mhpcc.edu myuserid
node6.class.mhpcc.edu myuserid
node7.class.mhpcc.edu myuserid
node8.class.mhpcc.edu myuserid
node9.class.mhpcc.edu myuserid
node10.class.mhpcc.edu myuserid

Parimal Sudas Page 127


node11.class.mhpcc.edu myuserid
node12.class.mhpcc.edu myuserid
node13.class.mhpcc.edu myuserid
node14.class.mhpcc.edu myuserid
node15.class.mhpcc.edu myuserid
node16.class.mhpcc.edu myuserid

3. Write the file to disk and exit the editor.


4. Make sure that the permissions on your .rhosts are set so that only you can
read/write the file:
5.
6. chmod 600 .rhosts

Remote login

7. Think of a machine other than the one you are logged into (node1-node16).
8. Then, use the remote login command to automatically login to the machine you
picked. For example:
9.
10. rlogin nodeXX.class.mhpcc.edu

You will notice that you are able to login without entering a userid or password.
Be sure to type n when asked to start mosaic.

11. Logout of the machine you just accessed

Remote copy

12. Think of a machine other than the one you are logged into (node1-node16).
13. Use the remote copy utility to copy one of your files to another machine's
temporary filespace. An example of what you might do appears below. Be sure
to substitute your chosen machine for "nodeXX" and your student userid for
"studntXX".
14.
15. rcp ~/Editors/maui.txt
nodeXX.class.mhpcc.edu:/tmp/studntXX.maui.txt

16. You will verify that the copy actually took place with a remote shell command in
the next exercise.

Remote shell

17. Using the same machine as you did for the remote copy command, remote shell
to that machine and list the contents of its temporary directory:
18.
Parimal Sudas Page 128
19. rsh nodeXX.class.mhpcc.edu ls -l /tmp

20. You should see the file you copied from the remote copy exercise.
21. Now, use rsh to remove that file - don't forget to substitute your userid for
"studntXX":
22.
23. rsh nodeXX.class.mhpcc.edu rm
/tmp/studntXX.maui.txt

24. Finally, use the remote shell command to look at all of the other machine's
student processes:
25.
26. rsh nodeXX.class.mhpcc.edu ps aux | grep studnt

What is X Windows?
• The X Window System is a network based graphical windowing system for workstations.
It was developed by MIT and has been adopted as an industry standard.
• X is supported by a consortium of industry leaders such as DEC, Sun, IBM, Hewlett-
Packard and AT&T. They have united to direct, contribute and fund the continuing
development of X.
• Most UNIX machines include X as part of their operating system. If you have "windows"
on your screen, chances are, you are using X, whether you are aware of it or not. It is
simply "part of your environment".
• The X Window System design is based upon the client-server model:
o Client: an application program which performs a specific task. For example, three
common X clients (xclock, xcalc, xterm) appear below:

Parimal Sudas Page 129


o Display Server: a program which acts as the intermediary between client
programs and the machine hardware. Keeps track of all user and client
input/output. Ordinarily, the display server program is started automatically for
you or, you start it once, and then forget about it.
• In conjunction with the X Window System, there is usually a Window Manager program
which allows you to control certain X client parameters:
o size of client
o location on screen
o whether or not client is iconified
o termination of client
• The topics of X Windows and window managers are very extensive. For more details,
consult any of the many references available.

Getting Started Using X Windows


• Three things must be done in order to use the X Window System:
1. Start the X display server
2. Start a window manager
3. Start the first instance of the xterm terminal emulator
• Starting the X display server. This may vary depending upon your local system.

o Some systems will start the X server for you automatically and provide you with
an initial login window. This is probably the case if you see a login screen that
looks something like the one below:

Parimal Sudas Page 130


o Other systems will start the X server for you automatically using something called
xdm. This is probably the case if you see a login screen that looks something like
the one below:

o Some systems require you to start the X server manually. This is usually done
with the "xinit" command. After logging in, you just type the command and let
the server do the rest.

After the server has started, you will see at least one xterm, and perhaps a couple
other xclients (clock, calculator, etc) too. This will depend upon your local
system.

o You can tailor the manner in which the X server starts by creating a file called
.xinitrc in your home directory. A sample .xinitrc from an IBM AIX system is
provided HERE.
U Starting the window manager.

Parimal Sudas Page 131


o A window manager is essential for working productively in the X Windows
environment. Many systems will start one for you automatically.
o There are several window manager programs in wide use. Those available to you
will depend upon your local system. Some common window managers are:
o
o uwm - Universal Window Manager
o twm - Tom's Window Manager
o mwm - Motif Window Manager
o awm - Ardent Window Manager
o rtl - Tiled Window Manager

o The easiest way to tell if a window manager is running is to look for a "border"
around your X clients. For example, an xclock with and without a border appears
below:

o If you need to start the window manager manually, simply type its name and put
the process in the background. For example, to start the Motif Window Manager:

mwm &

You may also be able to add a command as the last line of your .xinitrc file to
automatically start the window manager when you start the X server. For
example, to start the Motif Window Manager:

exec mwm

o After starting the window manager, your X clients will have borders and be able
to be controlled (move, resize, iconify, etc) via your keyboard and mouse.
U Starting the first xterm terminal emulator
o A terminal emulator is an X client that looks like a rectangular window and acts
as a terminal screen. It accepts input from you and will also display program
output. Most of the work you do will be done inside an xterm window.
o The most common terminal emulator xclient is called xterm.

Parimal Sudas Page 132


o At least one xterm should be started automatically whenever the X server is
started. If this doesn't happen, contact your local System Administrator for
assistance.
o If you want to open another xterm, type a command similar to the one shown
below at the first xterm's prompt:

xterm &

l Running X clients on other machines


o Because X Windows is a network based system, you can run X clients on
machines across the network and send their displays back to the machine which is
in front of you.
o You can also run an X client on any network machine and send its display to any
other network machine, provided that the necessary permissions are setup.
o To run an X client on another machine:
1. Give the other machine permission to send X displays to your local
machine with the xhost command:

xhost +othermachine

2. Start the X client on the other machine. This can be done at least three
different ways:
1. Use the rsh command and include the -display option. For
example, the following command will start an xterm on machine
kanaha and send the display back to machine makena. Note that in
most cases, the display machine name must be suffixed with ":0".

rsh kanaha xterm -display makena:0 &

2. Login to the other machine and start the X client there after you set
the DISPLAY environment variable to point to your local machine.
Again note that the display machine name must be suffixed with
":0".
3.
4. telnet kanaha
5. { enter userid and password }
6. setenv DISPLAY makena:0 &
7. xterm &

8. Login to the other machine and start the X client there using the
-display option to point to your local machine.
9.
10. telnet kanaha
11. { enter userid and password }
12. xterm -display makena:0 &

Parimal Sudas Page 133


Using the Window Manager
The following discussion pertains to the Motif Window Manager. Other window managers will
have similar functionality but behave differently. This discussion also assume a basic familiarity
with using a mouse.

• Root Menu
o The Root Menu provides a pop-up list of the basic window manager functions.
Some of these functions include:
o
o New Window - open a new xterm
o Resize - resize window
o Move - move window
o Lower - put window below other windows
o Raise - put window above other windows
o Shuffle Up - raise window one level
o Shuffle Down - lower window one level
o Refresh - refresh window
o Clients - pop-up list of X clients
o Restart - restart the window manager
o Quit - quit the window manager

oThe Root Menu will appear if you press and hold the right mouse button. Make
sure that the pointer is not pointing on an X client - it should be pointing to an
open area on the screen.
o You can select a function from the Root Menu by holding the mouse button and
sliding the pointer until the desired function is highlighted/raised. Releasing the
mouse button will select the function.
• Window Frame
o The window frame surrounds the X client and consists of
 title area
 minimize button
 maximize button
 window menu button
 four sides
 four corners

A sample window frame which surrounds an xterm appears below.

Parimal Sudas Page 134



o Title area: In addition to displaying the client's title, the title area is used to move
the window. To move the window, place the pointer over the title area, press the
left mouse button and drag the window to a new location. A wire frame is moved
during the drag to indicate the new location. When the button is released, the
window is moved to the new location.

Also selected window functions (move, resize, lower, etc) can be displayed by
placing the mouse cursor on the title bar and holding down the middle mouse
button.

o Minimize button: Located in the upper right hand corner. To turn the window into
an icon (an icon is a small image), click the left mouse button on the Minimize
button
o Maximize button: Located in the upper right hand corner. To make the window
fill the screen click the left mouse button on the Maximize button
o Window Menu button: Located in the upper left hand corner. To pull down the
window menu, place the pointer over the button and press the left mouse button.
While pressing the button, drag the pointer on the menu to your selection and
release the button when your selection is highlighted.
o Sides and Corners: Any of the four sides or corners can be used to resize the
window. Simply place the pointer over the frame component and press the left
mouse button. While holding the button, drag the pointer in the desired direction.
A wire frame is moved during the drag to indicate the new size. When the button
is released, the window is resized.
• Special Keys

Parimal Sudas Page 135


o In addition to using the mouse to select window manager functions, you may also
use "special keys" to accomplish the same tasks.
o Which keys are "special" depends upon your local system. In most cases they are
the CTRL, ALT and Function keys. For example:
o
o ALT + F3 - lower window
o ALT + F4 - close window
o ALT + F5 - restore window
o ALT + F7 - move window
o ALT + F8 - resize window
o ALT + F9 - minimize window
o ALT + F10 - maximize window

o Special keys may also be used in combination with the mouse buttons. For
example:
o
o ALT + left button - lower window
o ALT + middle button - resize window
o ALT + right button - move window
o CTRL + left button - xterm client: options menu
o CTRL + middle button - xterm client: vt options
o CTRL + right button - xterm client: vt fonts

• Cutting and Pasting


o The mouse can be used to cut text from any window and paste it into any other
window. This feature saves time and helps eliminate typos.
o To select text, place the pointer at the beginning of the text and then press and
hold the left mouse button. As you drag the mouse, the selected text will be
highlighted by reverse video. The pointer is your guide to text selection.
o When you have selected the desired text, release the mouse button. The "cut" text
will be stored in a buffer.
o Place your pointer in any window which accepts text, and then click the middle
button to "paste" the text. Note that if you are in the vi editor, your paste will need
to be done while the vi session is in "input" mode.
o Cutting and pasting can be done on the command line also.
• Widgets
o X clients frequently display buttons, scroll bars and slider bars to permit
interaction. In most cases, the mouse is used to interact with these "widgets"
o Buttons: click with the left mouse button (in most cases)
o Scroll bars: clicking with the left mouse button will usually scroll one line/screen,
depending where you click. The scroll bar can often be "grabbed" by pressing and
holding the middle mouse button and then dragging to the desired point.
o Slider bars: work like scroll bars.
o Other widgets: usually intuitive - experiment.
• Customizing your window manager

Parimal Sudas Page 136


o The default behavior of your window manager is usually defined in a system
configuration file. For example, the default configuration file for the Motif
Window Manager might be defined in /usr/lib/X11/system.mwmrc .
o Most window managers permit you to define your own configuration file. Motif,
for example, can be configured by a file called .mwmrc in your home directory.
o A sample Motif configuration file may be here.
o Additional details on constructing your Motif configuration file can be found in
the mwm man page .

Customizing Your X Clients


• Default X client resource specifications are usually kept in the directory:
/usr/lib/X11/app-defaults
• Most X clients permit you to customize various parameters, such as geometry (size),
color and fonts.
• Customizations can be specified as command line options or in an "X Resources" file,
called .Xdefaults located in your home directory.
• Some common command line options are listed below.

• -background - background color
• -bg - background color
• -foreground - foreground color
• -fg - foreground color
• -bordercolor - color of window border
• -bd - color of window border
• -borderwidth - border width
• -bw - border width
• -font - font for text
• -fn - font for text
• -display - display for client
• -geometry - window size and placement
• -iconic - start window as an icon
• -name - name to display on title bar
• -title - name to display on title bar

• In order to do further customization via an .Xdefaults file, you need to know the actual
resource specification. These are unique for each X client. An example .Xdefaults file can
be viewed here.
• Colors
o Many X clients allow you to alter their default colors. The colors available to you
will depend upon your system, but can usually be found by reviewing the file:
/usr/lib/X11/rgb.txt

Parimal Sudas Page 137


o X colors are specified as RGB values. Each color is a composite of three
primaries (Red, Green, Blue). The intensity of each primary is specified as a value
from 0 to 255. For example, the rgb.txt mappings for several colors appear below:
o
o 255 0 0 Red
o 0 255 0 Green
o 0 0 255 Blue
o 255 240 245 LavenderBlus
o 255 228 225 MistyRos
o 240 255 255 azur
o 224 238 238 azure2
o 93 205 205 azure3

o X client colors can often be set with command line options. In the example below,
an xterm is created with a blue background and white foreground (text):

xterm -bg blue -fg white &

o For more detailed (and permanent) color specifications, the .Xdefaults file can be
used. For example, the following lines might be used to set xterm colors:
o
o xterm*background: DarkSlateBlue
o xterm*foreground: LemonChiffon
o xterm*cursorColor: red
o xterm*pointerColor: red

o Although it is usually easiest to just use the color name, colors can also be
specified in hexidecimal format. This may be useful if you need a color that isn't
available on the system by name:
o
o #000000 black
o #FF0000 red
o #00FF00 green
o #0000FF blue
o #00FFFF cyan
o #5F9F9F cadet blue

• Fonts
o Many X clients permit you to specify alternate font(s) for text. The fonts which
are available to you depend upon your system, but they can usually be found by
reviewing the file: /usr/lib/X11/fonts/fonts.dir.

You can also use the xlsfonts utility to list all of your system's available fonts.

o Full font specifications are very detailed. Wildcards (*) can also be used. For
example:

Parimal Sudas Page 138


• 1 2 3 4 5 6 7 8 9 10 11 12
• -adobe-courier-bold-o-normal--10-100-75-75-m-60-iso8859-1
• -adobe-helvetica-bold-r-normal--*-120-*-*-*-*-iso8859-*

• 1= foundry
• 2 = font family
• 3 = weight
• 4 = slant
• 5 = set width
• 6 = pixels
• 7 = points (in tenths)
• 8 = horizontal resolution in d.p.i.
• 9 = vertical resolution in d.p.i.
• 10 = spacing
• 11 = average width (in tenths of a pixel)
• 12 = character set

o The xfd utility is helpful for viewing a font before you actually use it. For
example:

xfd -fn Rom14

A sample xfd display can be viewed here.

o Specifying a font with a command line option:

xterm -fn Rom14 &

o Specifying fonts in the .Xdefaults file:


o
o Mwm*fontList: -ibm--medium-r-medium--20-14-100-100-c-90-*
o *icon*fontList: fixed
o aixterm*font: Rom14.500
o Vt*.fontList: Rom10
o emacs*font: Rom14.500

• Geometry
o All X clients that display in a window allow you to specify their size and location
on the screen by using the geometry option:
o The syntax is:
o
o -geometry width x height +/- xoffset +/- yoffset
o
o width = in pixels usually; in characters for xterm
o height = in pixels usually; in rows for xterm
o +xoffset = pixels from left edge of screen
o -xoffset = pixels from right edge of screen

Parimal Sudas Page 139


o +yoffset = pixels from top edge of screen
o -yoffset = pixels from bottom edge of screen
o

o Example 1: Creates an xclock 125 pixels wide by 125 pixels high and places it 10
pixels from the right edge of the screen and 20 pixels from the top of the screen.

xclock -geometry 125x125-10+20 &

o Example 2: Creates an xterm 132 characters wide by 40 rows and places it 10


pixels from the right screen edge and 350 pixels from the top of the screen.

xterm -geometry 132x40-10+350 &

Some Common X Clients


A list of some common X clients appears below. Note that there are many X clients available
which do not appear here. Also, some of the clients in the list below are linked to their man page.
For additional information, consult an X Windows reference.

• bitmap - system bitmap editor and conversion utilities


• resize - reset terminal settings to current window size
• xbiff - mailbox flag
• xcalc - scientific calculator
• xclipboard - text clipboard
• xclock - continuous analog or digital clock
• xdm - X display manager
• xdpr - dump an X window display to a printer
• xedit - simple text editor
• xfd - font displayer
• xhost - server access control program
• xinit - X server initializer
• xkill - kill an X client
• xload - load average display
• xlogo - display the X logo
• xlsfonts - list fonts
• xmag - magnify parts of the screen
• xman - display man pages
• xmh - X Window interface to MH mail system
• xmodmap - keyboard and pointer modifier
• xpr - print an X window dump
• xprop - display window and font properties for X
• xrdb - X server resource database utility
• xrefresh - refresh all parts of an X screen
• xset - set user preference options
Parimal Sudas Page 140
• xsetroot - set root window parameters
• xterm - terminal emulator window
• xwd - create X Window dump
• xwininfo - display window information
• xwud - display (undump) an X window dump file

Parimal Sudas Page 141

You might also like